Associative Array Length Help

Hi all, this is my first post to sitepoint’s forums. Too bad it has to be with a question and not with some help. I’m somewhat of a newbie to the programming scene. I’ve taken a few C++ and VB courses in college, but this is my first attempt at JavaScript (which doesn’t seem to be too much different so far).

So… here’s my problem. I just started reading Simply JavaScript, which is really well written. So far I’m in chapter two and in the arrays section where the introduction to Associative arrays is taught. The previous section teaches that a regular array has a method called length which will tell you how many elements your array contains, example below:


var array1 = ["Element0", "Element1", "Element2"];
var elementsTotalInArray = array1.length;

The above code would output 3 if it were to be printed to the screen.

However, when I try to do the same thing with an Associative array I get 0 as my answer. Example code below:


var array1 = [];
array1["Key1"] = "Element0";
array1["Key2"] = "Element1";
array1["Key3"] = "Element2";
var elementsTotalInArray = array1.length;

I assume this is because we aren’t using the array container/object in the same fashion as the first example, so what exactly is going on here?

Try doing that with the Date object, or other objects, and you’ll find that you can also set and retrieve the values.

Bad idea, but it works:


var array1 = new Date();
array1["Key1"] = "Element0";
array1["Key2"] = "Element1";
array1["Key3"] = "Element2";
var key1Element = array1['Key1'];

Why this works is that you’re not actually setting what you think of as an associative array. Instead, you are setting new properties on the array1 object itself.
So array1[Key1] = ‘Element0’ is like doing array1.Key1 = ‘Element0’

JavaScript does not have associative arrays. The Mozilla developers network documentation about arrays actually states that you shouldn’t use an array for associative arrays, and links to an article on [url=“http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/”]JavaScript Associative Arrays Considered Harmful.

Instead, you should use an object for associative arrays instead. You won’t be able to use the normal array methods on associative arrays, but this Quirksmode article on associative arrays has some info on how you can use them.

For example:


var assocArray = {},
    item;
assocArray["Key1"] = "Element0";
assocArray["Key2"] = "Element1";
assocArray["Key3"] = "Element2";
for (item in assocArray) {
    if (assocArray.hasOwnProperty(item)) {
        // do stuff with assocArray[item]
    }
}