JavaScript Associative Arrays

Using associative arrays in javascript
home    JS Main  |  Basics  |  Advanced  |  Complete List

Home/JavaScript/Advanced/Arrays 2

Browser Compatibility:    NS3+, IE4+

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.





Other Topics: ASP/PHP | DHTML | Java

The tutorials and articles on these pages are © 1997-2010 by John Pollock and may not be reposted without written permission from the author, and may not be reprinted for profit. Disclaimer.

previous
Previous
By: John Pollock next
Next


Main Page  |  HTML  |  JavaScript  |  Graphics  |  DHTML/Style Sheets  |  ASP/PHP
PutWeb/FTP  |  CGI/Perl  |  Java  |  Design Articles
Privacy  |  Contact

Copyright © 1997-2010 The Web Design Resource. All rights reserved. Disclaimer.