Associative Arrays in Javascript
By Chris
12/08/2011
Documentation from Another Site:
So we have to use one of JavaScript's minor mysteries. In JavaScript, objects are also associative arrays (or hashes). That is, the property
theStatus.Home
can also be read or written by calling
theStatus['Home']
Thus, you can access each property by entering the name of the property as a string into this array. Such an array associates each keywith a value (in this case the key Home is associated with the valuenormal). In the Perl programming language it is also called a hash.
Unlike Perl, which requires you to create such an associative array explicitly, JavaScript automatically creates a associative array for each object.
You see this behaviour with common objects like a form. You can access a form by performing either of these DOM calls:
document.forms['theForm']
document.forms.theForm
(You can also use document.theForm but that's a special case, not regular behaviour of JavaScript objects/associative arrays).
So when we want to set the status of each image to 'normal' in our object, we do
var x = document.images;
for (var i=0;i<x.length;i++)
{
var theName = x[i].name;
theStatus[theName] = 'normal';
}
and it works. Now theName (a string) is put into the brackets [] where a string is expected. So you create a new key/value pair, which is the same as a new property with a value.
All this is JavaScript magic at its fullest. I don't completely understand what I'm doing either, but it works just fine. Basically you now have the power to let one name or string refer to another one.
My Example
The code is so simple yet so nice to have. _loadedSounds is my variable (global). I instantiate a new object and then I can just reference it as an associative array. Note, I must instantiate it as a new Object for it to work:
_loadedSounds = new Object();
$('.pnlPlayer').each(function(i, current) {
var id = $(current).attr("id");
var dataFile = $(current).attr("data-file");
_loadedSounds[id] = new buzz.sound(dataFile, {
preload: 'metadata',
autoplay: false,
loop: false
});
_loadedSounds[id] = dataFile;
});