How to check if object has any properties in JavaScript?

后端 未结 16 2324
自闭症患者
自闭症患者 2020-12-04 08:10

Assuming I declare

var ad = {}; 

How can I check whether this object will contain any user-defined properties?

16条回答
  •  爱一瞬间的悲伤
    2020-12-04 08:45

    You can use the following:

    Double bang !! property lookup

    var a = !![]; // true
    var a = !!null; // false
    

    hasOwnProperty This is something that I used to use:

    var myObject = {
      name: 'John',
      address: null
    };
    if (myObject.hasOwnProperty('address')) { // true
      // do something if it exists.
    }
    

    However, JavaScript decided not to protect the method’s name, so it could be tampered with.

    var myObject = {
      hasOwnProperty: 'I will populate it myself!'
    };
    

    prop in myObject

    var myObject = {
      name: 'John',
      address: null,
      developer: false
    };
    'developer' in myObject; // true, remember it's looking for exists, not value.
    

    typeof

    if (typeof myObject.name !== 'undefined') {
      // do something
    }
    

    However, it doesn't check for null.

    I think this is the best way.

    in operator

    var myObject = {
      name: 'John',
      address: null
    };
    
    if('name' in myObject) {
      console.log("Name exists in myObject");
    }else{
      console.log("Name does not exist in myObject");
    }
    

    result:

    Name exists in myObject

    Here is a link that goes into more detail on the in operator: Determining if an object property exists

提交回复
热议问题