一、方法一
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));
二、方法二
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());
三、方法二
var testObj = {
name1: "value1",
name2: "value2"
};
alert(Object.getOwnPropertyNames(testObj).length);