我非常喜欢解构和可选 chaining Javascript 中的提案。
我忍不住觉得,当解构一个 null 或未定义的值时,如果结果是未定义的,就像在可选链中一样,而不是抛出错误,那将非常有用。
例如:
const person = null
console.log(person?.age) // undefined
但是:
const person = null
const { age } = person // runtime error
当然它不是这样工作的,但是有一些 Babel 建议来添加这个功能吗?有什么解决办法吗?
最佳答案
听起来您可能只想使用 || {}
在 person
为 null 的情况下解构一个空对象(如果它也为 false,则恰好也适用):
const person = null
const { age } = person || {};
console.log(age);
关于javascript - 如何保护代码免于解构 Javascript 中的空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58077661/