javascript - 如何保护代码免于解构 Javascript 中的空值?

标签 javascript nullable destructuring

我非常喜欢解构和可选 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/

相关文章:

javascript - CSS flex display 与 Chrome 中的相同 flex 元素不同

javascript - 带有比较运算符的 jQuery DataTables 过滤列

.net - 何时在 F# 中引发 nullArg

java - 获取可选对象的字段或返回 null

javascript - 'next' 中的 'middleware function' 参数在 Node.js 的 Express 中如何工作?

javascript - 无法获取 Canvas 内容的 toDataURL

java - 我们应该始终使用@NotNull 还是@Nullable?

javascript - 解构 JavaScript 对象时如何只选择几个字段?

javascript - 从 Font Awesome 导入许多图标

javascript - 函数参数对象解构导致 undefined variable