js 獲取對象屬性個數

方法一:

var testObj = {
      name1: "value1",
      name2: "value2"
    };
alert(Object.getOwnPropertyNames(testObj).length); // 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章