SoFunction
Updated on 2025-04-03

JS Summary of the method to obtain the number of object attributes

1. Method 1

var attributeCount = function(obj) {
    var count = 0;
    for(var i in obj) {
        if((i)) {  // It is recommended to add judgment. If there is no extended object attribute, you can not add it.            count++;
        }
    }
    return count;
}
var testObj = {
    name1: "value1",
    name2: "value2"
};
alert(attributeCount(testObj)); // 2

2. Method 2

function TestObj(name, age) {
 = name,
     = age
 }
 = function() {
var count = 0
for(pro in this) {
    if((pro)) { // The object is extended here, so it must be judged         count++;
         }
    }
    return count;
}
var testObj = new TestObj('name', 12);
alert(()); // 2

Three, Method Three

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

Interested friends can use the online tools of this site:http://tools./code/HtmlJsRunTest the above code running effect!

The third method I often use during the development process, which returns all the properties of the object through getOwnPropertyNames, directly calculates the length of the properties, avoiding js traversal-related operations.