JS 实现获取对象属性个数的方法小结

一、方法一

  1. var attributeCount = function(obj) {
  2.      var count = 0;
  3.      for(var i in obj) {
  4.      if(obj.hasOwnProperty(i)) { // 建议加上判断,如果没有扩展对象属性可以不加
  5.          count++;
  6.      }
  7.      }
  8.      return count;
  9. }
  10. var testObj = {
  11.      name1: “value1”,
  12.      name2: “value2”
  13. };
  14. alert(attributeCount(testObj)); // 2

二、方法二

  1. function TestObj(name, age) {
  2.   this.name = name,
  3.      this.age = age
  4.  }
  5. TestObj.prototype.proCount = function() {
  6.   var count = 0
  7.   for(pro in this) {
  8.    if(this.hasOwnProperty(pro)) { // 这里扩展了对象,所以必须判断
  9.    count++;
  10.   }
  11.      }
  12.      return count;
  13. }
  14. var testObj = new TestObj(‘名称’, 12);
  15. alert(testObj.proCount()); // 2

三、方法三

  1. var testObj = {
  2.   name1: “value1”,
  3.   name2: “value2”
  4. };
  5. alert(Object.getOwnPropertyNames(testObj).length); // 2

感兴趣的朋友可以使用本站在线工具:http://tools.jb51.net/code/htmljsRun 测试上述代码运行效果!

笔者在开发过程中比较常用的是第三种方法,通过getOwnPropertyNames返回对象所有属性,直接计算属性的长度,避免了js遍历相关操作。

标签

发表评论