Initialize a Javascript Associative Array
There are a few thoughts we have to take note about Javascript Associative Arrays:
- Arrays (which act as hash tables) have nothing to do with the built-in
Arrayobject. They simply rely on the fact thatobject.propertyis the same asobject["property"]. This means that thelengthproperty is not used, nor do anyArraymethods (such asjoin) do anything. - The way to iterate over the items in an associate array is to use the
for (value in array)construct, allowing you to access each item’s value viaarray[value].
Initialize a Javascript Associative Array:
var animals = {"cat": 0, "dog": 1, "mouse": 2, "cow": 3, "horse": 4, "pig": 5,
"duck": 6, "goat": 7, "sheep": 8, "lion": 9};
Here’s a short example of doing the For Each loop equivalent in JavaScript:
for( var animals in names )
{
alert( names[i] );
}























Leave your response!