Can an Object be false?

前端 未结 9 1591
温柔的废话
温柔的废话 2020-12-06 04:35

Is there any way to make an object return false in javascript?

var obj = new Object();

console.log(!!obj) // prints \"true\" even if it\'s empty
         


        
9条回答
  •  借酒劲吻你
    2020-12-06 04:52

    No. But null will convert to false.

    > typeof(null)
    "object"
    > null instanceof Object
    false
    > !!null
    false
    

    To see if the object contains any properties, use (shamelessly copied from How do I count a JavaScript object's attributes?):

    function isEmpty (obj) {
        for (var k in obj) 
           if (obj.hasOwnProperty(k))
               return false;
        return true;
    }
    

提交回复
热议问题