[Javascript] multidimensional associative arrays

Nick Fitzsimons nick at nickfitz.co.uk
Wed Oct 5 03:10:57 CDT 2005


> associative array uses a word, not a number for the
> index.
>

In JavaScript, you can assign named properties to objects without any
fuss. Therefore, you can just use something like:

var hashmap = new Object();

hashmap['Gorillas'] = new Object();
hashmap['Gorillas']['alpha'] = 'Frank';
hashmap['Gorillas']['juvenile'] = 'Gus';


hashmap['Chimpanzees'] = new Object();
hashmap['Chimpanzees']['alpha'] = 'Charly';
hashmap['Chimpanzees']['juvenile'] = 'Isaac';

and so on.

You could also use:

hashmap.Chimpanzees = new Object();
hashmap.Chimpanzees.alpha = 'Charly';

but if the strings are potentially going to include reserved words or
weird characters, you're better off using the bracketed string method.
This means you can easily access properties using variables:

function retrieveApe(species, status) {
   return hashmap[species][status];
}

alert(retrieveApe("Chimpanzees", "juvenile"));

will give you 'Isaac'.

 If you're not cataloguing an assortment of apes, feel free to change the
names :-)

HTH,

Nick.
-- 
Nick Fitzsimons
http://www.nickfitz.co.uk/




More information about the Javascript mailing list