Daily Archives: October 7, 2008

JavaScript Associative Arrays (HashMaps) & Prototype.js & Object

Today I spent a lot of time figuring out what’s going on with the for loop over an Array. Finally realized what’s going on and hence this post.

In JavaScript, if you need to create associative arrays (hashmaps), then there are two ways to do it. Actually, there is only one way, but I will get to that in a minute.

var hmap = new Array();
hmap[0] = “hello”;
hmap[1] = “world”;

Here, the hmap array is used as a normal array.

var hmap = new Array();
hmap[“abc”] = “hello”;
hmap[“def”] = “world”;

is perfectly valid. Here, the hmap is used as an associative array. So far so good.

I had a bit of code where I loop through the keys of the hashmap and need to make use of both the keys and the values. So, the code was something like

for(var key in hmap) {
// do something with key and hmap[key]
}

I remember doing this several times in the past without any problem. But today, when using this pattern along with prototype.js, I ended up getting, in addition to the keys I put in, additional keys starting with “each”. Where the heck is this “each” and a whole bunch of other keys coming from? After a bit of digging I found Array @ prototypejs.org article that the prototype.js script actually adds several useful methods to the Array. And the right way to access the elements in the Array is to use the hmap.each method that enumerates all the elements. But in my case, I want both the key and value, so I couldn’t use this method.

After some more reading, I finally realized that it’s actually the Objects that are associative arrays in JavaScript. That means, rather than using Array for the hmap, I could simply use Object. So, by changing the code from

var hmap = new Array();

to

var hmap = new Object();

I could use the regular

for(var key in hmap) { /* do something with key and hmap[key] */ }

without any problem inspite of using prototype.js

Interesting how things could go wrong with prototype based languages, no pun intended.

Advertisements

1 Comment

Filed under javascript