JS/ES6:未定义的解构

新手上路,请多包涵

我正在使用这样的解构:

 const { item } = content
console.log(item)

但是我应该如何处理 content === undefined 这会引发错误?

“旧”方式如下所示:

 const item = content && content.item

因此,如果 content 未定义 -> item 也将是未定义的。

我可以使用解构做类似的事情吗?

原文由 user3142695 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 261
2 个回答

如果 content 是一个虚假值,您可以使用 短路评估 来提供默认值,在这种情况下通常是 undefinednull

 const content = undefined
const { item } = content || {}
console.log(item)                       // undefined

一种不那么惯用的( 见此评论)方法是在解构之前将内容传播到一个对象中,因为 nullundefineds 值被忽略

 const content = undefined
const { item } = { ...content }
console.log(item) // undefined

如果你正在解构函数参数,你可以提供一个默认值(示例中的 = {} )。

注意: 仅当解构参数为 undefined 时才会应用默认值,这意味着解构 null 值将引发错误。

 const getItem = ({ item } = {}) => item
console.log(getItem({ item: "thing" })) // "thing"
console.log(getItem())                  // undefined

try {
  getItem(null)
} catch(e) {
  console.log(e.message)                // Error - Cannot destructure property `item` of 'undefined' or 'null'.
}

如果输入对象不包含该属性,甚至可以为 item 属性设置一个默认值

 const getItem = ({ item = "default" } = {}) => item
console.log(getItem({ item: "thing" })) // "thing"
console.log(getItem({ foo: "bar" }))    // "default"

原文由 Ori Drori 发布,翻译遵循 CC BY-SA 4.0 许可协议

const { item } = Object(content)

原文由 Вадик Орлов 发布,翻译遵循 CC BY-SA 4.0 许可协议

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