方法一:
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