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;



Select random element from a Javascript Array

Need to select a random element from a javascript array? The process is fairly straightforward but I was not clever enough to figure it out on my own. First take a random number with Math.random() [which will return a random number between 0 and 1] then multiply this number by the length of the array. You then need to use Math.floor to round the number down to the nearest whole number and voila… you have a random element number. All of this can be included in the square brackets of the array to make more condensed/easy to read code.

For Example

randomElement = testArray[Math.floor(Math.random()*testArray.length)];