First let's see how an associative array is created;
var fruitBasket = new Array(); /*create it just like any other array*/
Then let's populate our fruitBasket with different types of fruits
fruitBasket["apple"] = 1; // there are one apple
fruitBasket["orange"] = 3; // three oranges and
fruitBasket["lemon"] = 2; // two lemons in our fruit basket
Now, let's retrieve the value associated with a key. For instance, let's retrieve and print the count of "apple".
document.print(fruitBasket["apple"]);
I'm interested in the whole content of my fruitBasket. I want to print it. But how can I retrieve it? Assuming that the keys of the associative arrays are objects (fruits of type String in our example), it is quite easy to guess that we can't access them the way we did with plain arrays. So fruitBasket[0] won't return me the first fruit in the basket. Let's see how we can accomplish it.
for(var fruit in fruitBasket){ /*for each key in the associative array*/
// write the key (fruit name)
document.write(fruit+"=");
/* write the value associated with the key (fruit count)*/
document.write(fruitBasket[fruit]+", ");
}
Now, allow me to complicate things a little bit. I throw two more apples and three more lemons in the basket. So we have to add 2 apples and 3 lemons to the corresponding counts. Let's accomplish it using our fruitBasket.
/* fruitBasket["apple"] returns the value associated with the key "apple" which is its count in the fruitBasket. */
fruitBasket["apple"] = fruitBasket["apple"] + 2; // add 2 to the actual count
fruitBasket["lemon"] = fruitBasket["lemon"] + 3; // add 3 to the actual count
I want to add a new fruit type to the basket, but first I want to check if it is really a new fruit or an existing one in the basket. Assume that I want to add 2 bananas to the basket.
/*
I try to retrieve the value associated with the key "banana". If there's no such a key then it'll return "null".
*/
if( fruitBasket["banana"] == null ){ // no banana in fruit basket
/* create a banana key and give it 2 as value, that is, add 2 bananas to our fruitBasket*/
fruitBasket["banana"] = 2;
}
To sum up, I tried to show how an associative array is created, how its key-value pairs should be retrieved and how to add new key-value pairs to the associative array.