[英]How to check if Javascript array of objects has the same value throughout
I have the following array:我有以下数组:
distributors = [{ Name: 'Foo', Count: 0}, { Name: 'Bar', Count: 0}, { Name: 'Baz', Count: 0}]
How do I check if the 'Count' is 0 for every object in the array?如何检查数组中每个 object 的“计数”是否为 0? Ideally, I would like to write a function to return boolean if the value for 'Count' is 0 for every object in the array.
理想情况下,如果数组中每个 object 的“计数”值为 0,我想编写一个 function 以返回 boolean。
You can use every method.您可以使用每种方法。 Every method checks if all elements in an array pass a test and returns true or false based on the function you have provided.
每个方法都会检查数组中的所有元素是否都通过了测试,并根据您提供的 function 返回 true 或 false。 So, If every element pass the test it returns true otherwise false.
因此,如果每个元素都通过测试,则返回 true,否则返回 false。
const distributors = [ { Name: 'Foo', Count: 0 }, { Name: 'Bar', Count: 0 }, { Name: 'Baz', Count: 0 }, ]; const ret = distributors.every((x) => x.Count === 0); console.log(ret);
This function returns true if all the Count property is 0如果所有 Count 属性为 0,则此 function 返回 true
function checkCount(distributors) {
for (let element of distributors) {
if (element.Count) {
return false;
}
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.