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!