PageResource.com - Web Development Tutorials

JavaScript Associative Arrays

Using associative arrays in javascript

Associative arrays give you another way to store information. Using associative arrays, you can call the array element you need using a string rather than a number, which is often easier to remember. The downside is that these aren't as useful in a loop because they do not use numbers as the index value.

An associative array is defined just like a regular array, but we insert some text in the place we had numbers in the regular arrays:

var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";

Now we can get the Word Mustang later in the script by remembering it is the "cool" car, so we would use my_cars["cool"]. This could be used to prompt a user to input the type of car he/she would prefer. Then you can send back what you think the viewer should buy based on the input:

 
<SCRIPT language="JavaScript">
<!--
function which_car()
{
var my_cars= new Array()
my_cars["cool"]="Mustang";
my_cars["family"]="Station Wagon";
my_cars["big"]="SUV";

var car_type=prompt("What type of car do you like?","");

if ((car_type=="cool") || (car_type=="family") || (car_type=="big"))
  alert("I think you should get a(n) "+my_cars[car_type]+".");
else
  alert("I don't really know what you should get. Sorry.");
}
//-->
</SCRIPT>
<FORM>
<INPUT TYPE="button" onClick="which_car()" value="Go!">
</FORM>

You can try it out with the button below. Of course, most of the time you will end up with the "I don't know" answer-- unless you happen to type in one of the three car types we used!

Well, that should take car of associative arrays for now. Try them out and see what kind of ideas you can come up with to make some useful scripts!

Well, that does it for now, Let's go on to the next section, Preloading Images.

previous
Previous
By: John Pollock next
Next

Copyright © The Web Design Resource. All rights reserved. | Contact Us | Privacy Policy