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

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

问题描述

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

I'm using some destructuring like this:

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

但是我应该如何处理 content === 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 未定义 -> item 也将未定义.

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

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

Can I do something similar using destructuring?

推荐答案

您可以使用 短路评估 以在 content 为假值时提供默认值,通常为 undefinednull 在这种情况下.

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

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

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天全站免登陆