解构赋值如果为null怎么让默认值生效?

每个解构属性都可以有一个默认值。当属性不存在或值为 undefined 时,将使用默认值。如果属性的值为 null,则不使用它。

阅读 5.3k
2 个回答

const { foo = 'default' } = null || {};

尽量不要在变量属性初始化时设为 null 特别是在你要使用 “默认值” 的时候。


贴一句尤大的在某一个 Issues 中的回复在这里,希望你可以明白其中的含意:

Hmm, yeah so it needs to be more accurate:

  • null indicates the value is explicitly marked as not present and it should remain null.
  • undefined indicates the value is not present and a default value should be used if available.
  • required: true indicates neither null or undefined are allowed (unless a default is used)

I agree this could be confusing, just as the existence of null vs. undefined in the language itself. But the design was trying to stay close to what these values are designed represent in JS, and changing them would be breaking.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏