Associative arrays in javascript have a similar task to associative arrays in any programming language; holding key-value pairs. If, for instance, our "keys" are fruits and the "values" associated to these keys are fruits' count in the basket then fruitBasket which holds these keys (fruits) and values (fruits' count) is the associative array.
First let's see how an associative array is created;
1 | var fruitBasket = new Array(); |
Then let's populate our fruitBasket with different types of fruits
1 | fruitBasket[ "apple" ] = 1; |
2 | fruitBasket[ "orange" ] = 3; |
3 | fruitBasket[ "lemon" ] = 2; |
Now, let's retrieve the value associated with a key. For instance, let's retrieve and print the count of "apple".
1 | 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.
1 | for ( var fruit in fruitBasket){ |
3 | document.write(fruit+ "=" ); |
5 | 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.
3 | fruitBasket[ "apple" ] = fruitBasket[ "apple" ] + 2; |
4 | fruitBasket[ "lemon" ] = fruitBasket[ "lemon" ] + 3; |
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.
4 | if ( fruitBasket[ "banana" ] == null ){ |
6 | 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.