How to check if object has any properties in JavaScript?

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

    var hasAnyProps = false; for (var key in obj) { hasAnyProps = true; break; }
    // as of this line hasAnyProps will show Boolean whether or not any iterable props exist
    

    Simple, works in every browser, and even though it's technically a loop for all keys on the object it does NOT loop through them all...either there's 0 and the loop doesn't run or there is some and it breaks after the first one (because all we're checking is if there's ANY...so why continue?)

提交回复
热议问题