[英]How does OR operator work in find function in javascript or typescript?
If I have an array of objects: 如果我有一个对象数组:
myArray = [
{id:123, name:"abc"},
{id:234, name:"xyz"},
{id:345, name:"pqr"}
]
someValue = 123
someOtherObj = {id: 234}
let matchedObj = this.myArray.find(object=> object.id === somevalue || object.id === someOtherObj.id)
console.log(matchedObj)
Would the output be 123 every time, or it could be 123 or 234? 每次输出是123,还是123或234? Can you explain how this works? 您能解释一下这是如何工作的吗?
find
finds the first matching entry in the array. find
查找数组中的第一个匹配条目。 condition1 || condition2
condition1 || condition2
is true if either condition1
or condition2
is true. condition1 || condition2
为真,如果任何 condition1
或 condition2
是真实的。 (More specifically: ||
evaluates its left-hand operand first, and if that result is truthy, takes that truthy value as its result; if the left-hand result is falsy, ||
evaluates its right-hand operand and takes that value as its result.) (更具体地说: ||
评估其左侧操作数,如果结果为真,则以该真实值作为结果;如果左侧结果为伪造, ||
评估其右侧操作数并获取该值结果)。
So with that sample data, it will always match the first entry, because it matches the condition and it's before the second entry (which also matches the condition). 因此,对于该样本数据,它将始终与第一个条目匹配,因为它与条件匹配并且位于第二个条目之前(也与条件匹配)。 But if the entries were in a different order, where the id: 234
were before the id: 123
, it would find that one instead: 但是,如果条目的顺序不同,则id: 234
在id: 123
之前,它将找到那个:
const someValue = 123; const someOtherObj = {id: 234}; function match(array) { console.log(array.find(object => object.id === someValue || object.id === someOtherObj.id)); } match([ {id:123, name:"abc"}, // Finds this one {id:234, name:"xyz"}, {id:345, name:"pqr"} ]); match([ {id:345, name:"pqr"}, {id:234, name:"xyz"}, // Finds this one {id:123, name:"abc"} ]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.