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";

This example shows the use of an associative array - assigning a person's name with the phone number

Name:

Number:

Here each person is given a default value and name in our drop down list

 

<select onChange = "displayNumber(phone_book, this.options[selectedIndex].value);">

<option value="bleary">bleary

<option value="weary">weary

<option value="dreary">dreary

<option value="sneery">sneery

</select>

And in javascript we associate a new array of each person's name with their phone number.


The code:


  1. Use the onChange event for our selection box to call the "displayNumber()" function

    <select onChange = "displayNumber(phone_book, this.options[selectedIndex].value);">

  2. Send in this first value: phone_book -- the name of our array of our phone numbers that are associated with each name

  3. Send in this value: "this.options[selectedIndex].value" -- well, it's the value of the selectedIndex of our options - the javascript given name for the options and index values for that select box.

    the "this." part - means the current one that is selected - it is something we use with objects -to reference itself.

    You know, you could memorize all this syntax, or ..... just remember where to find it and how to apply it. How to apply it is just practice - so just remember where to find it.

  4. So anyway, we send in "dreary" (if that's the one we just chose)

    function displayNumber(phone_book, entry)

  5. The phone_book array looks for the number that matches the name "dreary"

    var the_number = phone_book[entry];

  6. We stick that phone number into our textbox for the answer

    window.document.the_form.number_box.value = the_number;

<script language = "JavaScript">

<!-- hide me

var phone_book = new Array();

phone_book["bleary"] = "(203) 555-1234";

phone_book["weary"] = "(203) 555-2345";

phone_book["dreary"] = "(203) 555-4321";

phone_book["sneery"] = "(203) 555-3245";

//In this function, we display the number based on the person's name that was chosen.

function displayNumber(phone_book, entry)

{

var the_number = phone_book[entry];

window.document.the_form.number_box.value = the_number;

}

// -->

</script>