简体   繁体   English

更好的方法来检查字典上的所有值是否都是真的?

[英]Better way to check if all values on dictionary are true?

Ok, this is what i got: 好的,这就是我得到的:

var matchgrid = {
    "a1":[false, 0], "a2":[false, 0], "a3":[false, 0],
    "b1":[false, 0], "b2":[false, 0], "b3":[false, 0],
    "c1":[false, 0], "c2":[false, 0], "c3":[false, 0]};

var keys = Object.keys(matchgrid);

var ch = 0;

for (i=0;i<9;i++) {
        if (matchgrid[keys[i]][0] === false) {
            ch += 1;
        } else if (matchgrid[keys[i]][0] === true) {
            ch -= 1;
        }
    }

//then check it with:

if (ch === 9) {
    //do something
} else { 
    //do something else
}

as you can see, its a dictionary with arrays as values and i want to know if the first value of the all the keys is false , true or mixed, this works fine, but i'm sure that there's a better way to do it, any help? 正如你所看到的,它是一个以数组作为值的字典,我想知道所有键的第一个值是falsetrue还是混合的,这很好用,但我确信有更好的方法来做到这一点,任何帮助?

Your native JavaScript approach is fine. 你原生的JavaScript方法很好。 Rather than storing the sum you may just store a boolean, start it as true, then if you see a false, set it to false. 您可以只存储一个布尔值,而不是存储总和,将其设置为true,然后如果您看到false,则将其设置为false。 Then rather than check ch == 9 just check for the boolean. 然后检查ch == 9而不是检查布尔值。

However, if you can use underscore.js (which has a lot of useful functions for lists), one of those functions is called every that checks if every item passes the truth test. 但是,如果你可以使用underscore.js (其中有列出了很多有用的功能),这些功能中的一个被称为every如果每个项目通过事实测试检查。 Then it becomes as simple as this 然后变得如此简单

_.every(matchgrid, function(item) {
     return item[0];
})

Even shorter, and a little fancier: 更短,更有点发烧友:

_.every(matchgrid, _.first); // will return true if all elements are true
var ch = 0;

var result;
for (i=0;i<9;i++) {
        result = matchgrid[keys[i]][0];
        if (result) {
            break;
        } 
    }

// result will be false if they are all false

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

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