Home » javascript

Initialize a Javascript Associative Array

28 May 2009 970 views No Comment

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 Array object. They simply rely on the fact that object.property is the same as object["property"]. This means that the length property is not used, nor do any Array methods (such as join) 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 via array[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] );
}

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.