Can an Object be false?

前端 未结 9 1583
温柔的废话
温柔的废话 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 05:10

    Object-to-boolean conversions are trivial. All objects (including arrays and functions) convert to true. This is so even for wrapper objects (new Boolean(false)) is an object rather than a primitive value, and so it converts to true.

    0 讨论(0)
  • 2020-12-06 05:11

    In your case

    console.log(!obj); will return false.

    because an object or an empty object is always a truthy.

    0 讨论(0)
  • 2020-12-06 05:13

    A null "object" (really value) will return false.

    var obj = null;
    
    console.log(!!obj);
    

    If you wanted to check if it has no properties, you might try:

    var obj = new Object();
    var empty = true;
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
           empty = false;
           break;
        }
    }
    console.log(empty);
    
    0 讨论(0)
提交回复
热议问题