gpt4 book ai didi

javascript - 检查数组中是否有任何对象的值为 true?

转载 作者:行者123 更新时间:2023-12-02 17:37:16 24 4
gpt4 key购买 nike

我有一个看起来像这样简化的数组:

[{one: false,two: 'cat'},{one: true, two: 'dog'},{one: false, two: 'ball'}]

我想检查其中任何一个值是否为真。我能想到的解决方案是这样的

var truthness;
array.forEach(function (element, i, array) {
if(element.one){
truthness = true
break;
}
}

if(truthness){
//code
}else{
//other code
}

有更好的方法吗?

最佳答案

数组有一个方法 .some ,如果回调对于数组中的任何元素返回 true,则返回 true;如果返回 false,则返回 false对于数组中的每个元素。

var truthness = array.some(function(element) {
return element.one;
});

关于javascript - 检查数组中是否有任何对象的值为 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22513235/

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