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

Destructuring fallback to prevent undefined error?

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

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

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

这里的问题是 .find() returns 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);

希望对您有所帮助!