3.7.06

Associative arrays

If you still believe in Santa, stop reading.

Are you familiar with associative Arrays in JavaScript? Well, they're also referred to as hashtables. Guess what? They don't exist. You have been fooled.

The Array object, like all other JavaScript objects, inherits from the Object object --I can't find a way to not make this redundant... hmmm-- so when you think you're making an associative array, you really are only defining properties to the Array. The array itself can still have other elements (always retrieved by index)

var hashtable = new Array();
hashtable['uno'] = "The one";
hashtable['dos'] = "Two";

So far, so good. How do you iterate? you use a for in loop.

hashtable.push('foo');
hashtable[1] = 'gnarl';

How do you iterate? well... you could still use a for in loop, which would return you "The one" and "Two". However, what if you use a regular for i loop? Well, you'd get "foo" and "glarl". Is this odd? Can an array be both an associative array AND a regular array? Not at all! The reason is, THERE IS NO SUCH THING AS AN ASSOCIATIVE ARRAY.

Hey, I have a brilliant idea. Let's make an associative Boolean:

var isSupahCool = new Boolean();
isSupahCool['uno'] = true;
isSupahCool['dos'] = false;

NOT! --see, the boolean is still a boolean. I'm only defining properties for the Object it inherits from.

Don't get me wrong, this IS actually a supah cool way to bestow functionality to our objects, say, by making small beans:

var array = [];
array.contains = function (){...};
array.isLocked = false;

The array is still an array, but with other methods and properties that give it more pizazz. Does it mean that it's WRONG if you use an "associative array"? Not at all. It's just not the array you're using. You might as well use a slice of tuna.

var sushi = new SliceOfTuna();
sushi['california'] = 'yum';

You get the picture.

No comments: