繁体   English   中英

如何检查 Javascript 对象数组是否始终具有相同的值

[英]How to check if Javascript array of objects has the same value throughout

我有以下数组:
distributors = [{ Name: 'Foo', Count: 0}, { Name: 'Bar', Count: 0}, { Name: 'Baz', Count: 0}]

如何检查数组中每个 object 的“计数”是否为 0? 理想情况下,如果数组中每个 object 的“计数”值为 0,我想编写一个 function 以返回 boolean。

您可以使用每种方法。 每个方法都会检查数组中的所有元素是否都通过了测试,并根据您提供的 function 返回 true 或 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);

如果所有 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.

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