Javascript JS/ES6:未定义的解构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48433008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:06:40  来源:igfitidea点击:

JS/ES6: Destructuring of undefined

javascriptecmascript-6

提问by user3142695

I'm using some destructuring like this:

我正在使用一些这样的解构:

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

But how should I handle content === undefined- which will throw an error?

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

The 'old' way would look like this:

“旧”方式如下所示:

const item = content && content.item

So, if contentis undefined -> itemwill also be undefined.

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

Can I do something similar using destructuring?

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

回答by Ori Drori

You can use short circuit evaluationto supply a default if contentis a falsy value, usually undefinedor nullin this case.

您可以使用短路评估来提供默认值 if contentis a falsy value,通常undefinednull在这种情况下。

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

A less idiomatic (see this comment) way is to spread the content into an object before destructuring it, because nulland undefinedsvalues are ignored.

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

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

If you are destructuring function params you can supply a default (= {}in the example).

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

Note:The default value would only be applied if the destructured param is undefined, which means that destructuring nullvalues will throw an error.

注意:只有在解构参数为 时才会应用默认值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'.
}

Or even set a default value for the itemproperty if the input object doesn't contain the property

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

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

回答by Nir O.

accepted answer does not work for truely undefined values which were not set by const content = undefined. in such cases this will work:

接受的答案不适用于未设置的真正未定义的值const content = undefined。在这种情况下,这将起作用:

const { item } = (typeof content !== 'undefined' && content) || {}
console.log(item)

回答by Вадик Орлов

const { item } = Object(content)