如何保护代码免于解构 Javascript 中的空值?
How to protect code from destructuring a null value in Javascript?
我非常喜欢 Javascript 中的解构和可选的 chaining 提议。
我忍不住觉得,当解构一个 null 或未定义的值时,如果结果是未定义的,因为它在可选链中而不是抛出错误,那将非常有用。
例如:
const person = null
console.log(person?.age) // undefined
但是:
const person = null
const { age } = person // runtime error
它当然不是这样工作的,但是有没有一些 Babel 提议添加这个功能?有什么解决方法吗?
听起来你可能只想使用 || {}
来解构一个空对象,以防 person
为空(如果它也为假,则恰好也适用):
const person = null
const { age } = person || {};
console.log(age);
您可以使用 ||
、
的默认值
const person = null
const { age } = person || {}
console.log(age)
我非常喜欢 Javascript 中的解构和可选的 chaining 提议。
我忍不住觉得,当解构一个 null 或未定义的值时,如果结果是未定义的,因为它在可选链中而不是抛出错误,那将非常有用。
例如:
const person = null
console.log(person?.age) // undefined
但是:
const person = null
const { age } = person // runtime error
它当然不是这样工作的,但是有没有一些 Babel 提议添加这个功能?有什么解决方法吗?
听起来你可能只想使用 || {}
来解构一个空对象,以防 person
为空(如果它也为假,则恰好也适用):
const person = null
const { age } = person || {};
console.log(age);
您可以使用 ||
、
const person = null
const { age } = person || {}
console.log(age)