博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
js 获取对象属性个数
阅读量:7170 次
发布时间:2019-06-29

本文共 830 字,大约阅读时间需要 2 分钟。

方法一:

var attributeCount = function(obj) {        var count = 0;        for(var i in obj) {            if(obj.hasOwnProperty(i)) {  // 建议加上判断,如果没有扩展对象属性可以不加                count++;            }        }        return count;    }    var testObj = {        name1: "value1",        name2: "value2"    };    alert(attributeCount(testObj)); // 2

 

方法二:

  function TestObj(name, age) {      this.name = name,        this.age = age  }  TestObj.prototype.proCount = function() {      var count = 0      for(pro in this) {          if(this.hasOwnProperty(pro)) { // 这里扩展了对象,所以必须判断              count++;          }      }      return count;  }  var testObj = new TestObj('名称', 12);  alert(testObj.proCount()); // 2

 

方法三:

var testObj = {      name1: "value1",      name2: "value2"    };    alert(Object.getOwnPropertyNames(testObj).length); // 2

转载地址:http://bdqwm.baihongyu.com/

你可能感兴趣的文章