简体   繁体   English

使用默认值和三元运算符查找的可选链接方法

[英]Optional chaining method on find with default value and a ternary operator

i am trying to implement the optional chaining in array.find.我正在尝试在array.find 中实现可选链接。 see the below snippet code i have below three cases请参阅下面的代码片段我有以下三种情况

  1. if array is empty i need to have the true // by default true如果数组为空,我需要为真 // 默认情况下为真
  2. if the array didn't find the object it should also be true // empty as true value如果数组没有找到 object 它也应该为真 // 空为真值
  3. if the array has the object it should take the key property value // true or false如果数组具有 object 它应该采用键属性值 // true 或 false

But as per the 3 case, if the key value is false its taking the 2 one但是根据第 3 种情况,如果键值为 false,则取 2

 let array = [{ id: 1, key: false }, { id: 2, key: true }] let key = array && array.length? array.find( (item) => item.id === 1 )?.key || "empty as true value": "by default true"; console.log(key)

You cannot use ||你不能使用|| when the left-hand side value can be falsy.当左边的值可能是假的。 You will either need to use it on the object (which is truthy) before accessing the .key在访问.key之前,您要么需要在 object(这是真实的)上使用它

const key = (array?.find(item =>
  item.id === 1
) || {key: "empty as true value"}).key;

or better use the nullish coalescing operator :或更好地使用无效合并运算符

const key = array?.find(item =>
  item.id === 1
)?.key ?? "empty as true value";

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

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