gpt4 book ai didi

javascript - 解构回退以防止未定义的错误?

转载 作者:行者123 更新时间:2023-12-05 02:07:58 24 4
gpt4 key购买 nike

我有一个数组列表,我这样做:

const { id } = myArray.find(
(obj) => obj === true)

如果 id 不存在,它将抛出错误。如何在使用解构的同时防止出错?我想将逻辑保持在一行中。

最佳答案

这里的问题是.find()一旦条件不满足,返回 undefined:

The value of the first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

所以您可能可以使用 || 运算符来检查您是否有从 .find() 返回的任何值,或者您可以用空对象替换 {} 而不是在运算符的右侧。

可能单行的选项如下:

const myArray = [
{ id: 12 },
{ id: 13 },
{ id: 14 }
];

const { id } = myArray.find(e => e.id === 17) || {};

console.log(id);

所以你可以解构 id 属性,即使它以这种方式返回 undefined

此外,如果您需要,您可以根据说明 Destructuring statement 的文档将默认值添加到解构语句中如下:

A variable can be assigned a default, in the case that the value unpacked from the object is undefined.

const { id = 10 } = {};

console.log(id);

希望对您有所帮助!

关于javascript - 解构回退以防止未定义的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61360864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com