Wednesday, September 28, 2011

Number of elements in a javascript object

Number of elements in a javascript object


Although JS implementations might keep track of such a value internally, there's no standard way to get it.
On Mozilla-browsers, you can use the non-standard __count__, but for cross-browser scripting you're stuck with explicitly iterating over the properties and checking hasOwnProperty():
function countProperties(obj) { 
    var count = 0; 
 
    for(var prop in obj) { 
        if(obj.hasOwnProperty(prop)) 
                ++count; 
    } 
 
    return count; } 

For more info:   http://stackoverflow.com/questions/956719/number-of-elements-in-a-javascript-object?answertab=votes#tab-top

No comments:

Post a Comment