Gets the sample code for the number of Javascript object attributes

  • 2020-03-29 23:52:24
  • OfStack

As follows:

//Extends the count method of the object
Object.prototype.count = (
    Object.prototype.hasOwnProperty( ' __count__')
  ) ? function () {
    return this.__count__;
  } : function () {
    var count = 0;
    for (var i in this) if (this.hasOwnProperty(i)) {
      count ++;
    }
    return count;
  }; 

// use 
var myObj = {
    name1:  " value1 " ,
    name2:  " value2 " 
};

alert(myObj.count()); 

Related articles: