简体   繁体   English

解构后备以防止未定义的错误?

[英]Destructuring fallback to prevent undefined error?

I have a list of array I do this:我有一个数组列表,我这样做:

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

If the id is not present it will throw error.如果id不存在,则会抛出错误。 How to prevent error in the same time use destructuring?如何在使用解构的同时防止错误? I want to keep the logic in one line.我想将逻辑保持在一行中。

The issue here is .find() returns undefined once there is no fulfillment for the condition:这里的问题是.find()一旦条件不满足就会返回undefined

The value of the first element in the array that satisfies the provided testing function.满足提供的测试 function 的数组中第一个元素的值。 Otherwise, undefined is returned.否则,返回undefined

So probably you can use ||所以也许你可以使用|| operator to check if you have any value returned from .find() or you can replace with empty object {} instead on the right side of the operator.运算符来检查您是否有任何从.find()返回的值,或者您可以用空的 object {}代替运算符右侧的值。

Probably the option for one-liner is the following:单线的选项可能如下:

 const myArray = [ { id: 12 }, { id: 13 }, { id: 14 } ]; const { id } = myArray.find(e => e.id === 17) || {}; console.log(id);

So you can destructure id property even if it returned undefined in this way.所以你可以解构id属性,即使它以这种方式返回undefined

Also if you need you can add default value to your destructuring statement based on the documentation which states for Destructuring statement as follows:此外,如果您需要,您可以根据说明解构语句的文档为解构语句添加默认值,如下所示:

A variable can be assigned a default, in the case that the value unpacked from the object is undefined .如果从 object 解压缩的值是undefined ,则可以为变量分配默认值。

 const { id = 10 } = {}; console.log(id);

I hope this helps!我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM