How to know if all javascript object values are true?

前端 未结 5 904
再見小時候
再見小時候 2020-12-23 16:21

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

If I have the following object:

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


        
5条回答
  •  抹茶落季
    2020-12-23 17:01

    How about something like:

        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('
    myObj1 all true: ' + allTrue(myObj1)); document.write('
    myObj2 all true: ' + allTrue(myObj2));

    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.

提交回复
热议问题