How to check if object has any properties in JavaScript?

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

    You can loop over the properties of your object as follows:

    for(var prop in ad) {
        if (ad.hasOwnProperty(prop)) {
            // handle prop as required
        }
    }
    

    It is important to use the hasOwnProperty() method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.

    Edit

    From the comments: You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment

    Performance Test

    Test Of Object.Keys vs For..In When testing for any properties

提交回复
热议问题