How to check if object has any properties in JavaScript?

后端 未结 16 2313
自闭症患者
自闭症患者 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:50

    for (var hasProperties in ad) break;
    if (hasProperties)
        ... // ad has properties
    

    If you have to be safe and check for Object prototypes (these are added by certain libraries and not there by default):

    var hasProperties = false;
    for (var x in ad) {
        if (ad.hasOwnProperty(x)) {
            hasProperties = true;
            break;
        }
    }
    if (hasProperties)
        ... // ad has properties
    

提交回复
热议问题