如何知道所有的javascript对象值是否都为真? [英] How to know if all javascript object values are true?

查看:37
本文介绍了如何知道所有的javascript对象值是否都为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我需要知道是否所有对象项都设置为true.

In JavaScript, I need to know if all object items are set to true.

如果我有以下对象:

var myObj = {title:true, name:true, email:false};

我可以这样写:

 if(myObj.title && myObj.name && myObj.email){
 /*Some code */
};

但是我正在寻找最简单的编写方式.例如:

But I am looking for the simplest way to write it. eg :

if(myObj all is true){
/*Some code */
};

我可能有另一个带有10-20个项目的对象,并且将需要知道所有内容是否正确.

I might have another object with 10-20 items inside it, and will need to know if all are true.

推荐答案

诸如此类的事情

    function allTrue(obj)
    {
      for(var o in obj)
          if(!obj[o]) return false;
        
      return true;
    }
    
    var myObj1 = {title:true, name:true, email:false};
    var myObj2 = {title:true, name:true, email:true};

    document.write('<br />myObj1 all true: ' + allTrue(myObj1));
    document.write('<br />myObj2 all true: ' + allTrue(myObj2));

    

一些免责声明::如果所有值均为 true-ish (不一定完全等于布尔值True),则它将返回 true .此外,它将扫描传入对象的 all 所有属性,包括其原型.这可能是您的需要,也可能不是,但它在像您提供的对象这样的简单对象文字上应该可以正常工作.

A few disclaimers: This will return true if all values are true-ish, not necessarily exactly equal to the Boolean value of True. Also, it will scan all properties of the passed in object, including its prototype. This may or may not be what you need, however it should work fine on a simple object literal like the one you provided.

这篇关于如何知道所有的javascript对象值是否都为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆