简体   繁体   English

javascript(angularjs)检查js对象中是否存在值

[英]javascript (angularjs) check if value exists in js object

I have the following object 我有以下对象

{
  0 : false,
  1 : true,
  2 : false
}

What i need to do is i loop through these and set some of them to true or false depending on the condition but i need a function to check if all values are set to true or if false exists in the object. 我需要做的是我遍历这些并将它们中的某些条件设置为true或false,但我需要一个函数来检查对象中是否将所有值都设置为true或false。

I have the following to check if the value is false to do something 我有以下检查值是否为假做某事

 angular.forEach($scope.keyFiles, function (val, key) {
        if(val == false) {
              $scope.loadCanvas(key);
              return key;
        }
 });

but i need something now to check if false exists at all in any of the values and if all values are set to true. 但是我现在需要一些东西来检查任何值中是否都存在false以及是否所有值都设置为true。

Im new to javascript so excuse me if this sounds like a simple solution. 我是javascript新手,请问这听起来像是一种简单的解决方案。

Hope this is what you are looking for. 希望这是您想要的。

function containsFalse(obj){
    for(var prop in obj){
       if(obj[prop] === false) return true;
    }
    return false;
}

Here is a plain javascript way of doing it: 这是一种简单的javascript方法:

var keyFiles = {
  0 : false,
  1 : true,
  2 : false
};

var falseExists = false;
for (var prop in keyFiles) {
    if (keyFiles.hasOwnProperty(prop) && keyFiles[prop] === false) {
        falseExists = true;
        break;
    }
}

console.log(falseExists);

More on hasOwnProperty in this MDN link MDN链接中有关hasOwnProperty更多信息

In modern browsers (ie, IE 9+, Chrome 5+ etc) the code can be simplified as below: 在现代浏览器(即IE 9 +,Chrome 5+等)中,代码可以简化如下:

for (var prop in Object.getOwnPropertyNames(keyFiles)) {
    if (keyFiles[prop] === false) {
        falseExists = true;
        break;
    }
}

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

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