获得Javascript 对象的属性个数

  1. //扩展对象的count方法
  2. Object. prototype. count = (
  3.     Object. prototype. hasOwnProperty ( ‘__count__’ )
  4.   ) ? function () {
  5.     return this.__count__;
  6.   } : function () {
  7.     var count = 0;
  8.     for ( var i in this ) if ( this. hasOwnProperty (i )) {
  9.       count ++;
  10.     }
  11.     return count;
  12.   };
  13.  
  14. //使用
  15. var myObj = {
  16.     name1: “value1″,
  17.     name2: “value2″
  18. };
  19.  
  20. alert (myObj. count ());

你可能感兴趣的:(JavaScript,function,扩展)