How to check if object has any properties in JavaScript?

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

    What about making a simple function?

    function isEmptyObject(obj) {
      for(var prop in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, prop)) {
          return false;
        }
      }
      return true;
    }
    
    isEmptyObject({}); // true
    isEmptyObject({foo:'bar'});  // false
    

    The hasOwnProperty method call directly on the Object.prototype is only to add little more safety, imagine the following using a normal obj.hasOwnProperty(...) call:

    isEmptyObject({hasOwnProperty:'boom'});  // false
    

    Note: (for the future) The above method relies on the for...in statement, and this statement iterates only over enumerable properties, in the currently most widely implemented ECMAScript Standard (3rd edition) the programmer doesn't have any way to create non-enumerable properties.

    However this has changed now with ECMAScript 5th Edition, and we are able to create non-enumerable, non-writable or non-deletable properties, so the above method can fail, e.g.:

    var obj = {};
    Object.defineProperty(obj, 'test', { value: 'testVal', 
      enumerable: false,
      writable: true,
      configurable: true
    });
    isEmptyObject(obj); // true, wrong!!
    obj.hasOwnProperty('test'); // true, the property exist!!
    

    An ECMAScript 5 solution to this problem would be:

    function isEmptyObject(obj) {
      return Object.getOwnPropertyNames(obj).length === 0;
    }
    

    The Object.getOwnPropertyNames method returns an Array containing the names of all the own properties of an object, enumerable or not, this method is being implemented now by browser vendors, it's already on the Chrome 5 Beta and the latest WebKit Nightly Builds.

    Object.defineProperty is also available on those browsers and latest Firefox 3.7 Alpha releases.

提交回复
热议问题