JS / ES6:未定义的解构 [英] JS/ES6: Destructuring of undefined

查看:88
本文介绍了JS / ES6:未定义的解构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这样的解构:

I'm using some destructuring like this:

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

但我该如何处理内容=== undefined - 会抛出错误?

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

'旧'的方式如下所示:

The 'old' way would look like this:

const item = content && content.item

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

So, if content is undefined -> item will also be undefined.

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

Can I do something similar using destructuring?

推荐答案

您可以使用短路评估,如果内容是假值,则提供默认值,通常为<$ c $在这种情况下,c> undefined 或 null

You can use short circuit evaluation to supply a default if content is a falsy value, usually undefined or null in this case.

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

少一个惯用的(看到此评论)方式是传播在解构之前将内容转换为对象,因为 null undefineds 值被忽略

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

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

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

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

注意:只有在析构化的参数 undefined 时才会应用默认值,这意味着解构 null 值将引发错误。

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

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 属性设置默认值

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

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

这篇关于JS / ES6:未定义的解构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆