每个解构属性都可以有一个默认值。当属性不存在或值为 undefined 时,将使用默认值。如果属性的值为 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 remainnull
.undefined
indicates the value is not present and a default value should be used if available.required: true
indicates neithernull
orundefined
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.
9 回答9.4k 阅读
6 回答5.1k 阅读✓ 已解决
5 回答3.7k 阅读✓ 已解决
3 回答10.5k 阅读✓ 已解决
4 回答8k 阅读✓ 已解决
7 回答10.1k 阅读
4 回答7.4k 阅读
const { foo = 'default' } = null || {};