How to find the length of an associative array in JavaScript

So this little tidbit took me a bit by surprise. The .length property does not work on associative arrays in JavaScript. It will return zero no matter how many elements are in the array. Below is a script I found that will correctly return the length of a JavaScript associative array.

 

associativeArrayLength = function(obj)
{
    var size = 0, key;
    for (key in obj)
        {
        if (obj.hasOwnProperty(key)) size++;
        }
    return size;
};

 

Source: http://stackoverflow.com/questions/5223/length-of-javascript-associative-array

Comments are closed.