Using associative arrays

Associative arrays (also known as hash tables) allows you to use strings instead of index numbers.

Using associative arrays is more limited but they make the elements of the array easier to remember.

var StudentsClass = new Array();
StudentsClass["tall"] = "Dan";
StudentsClass["beautiful"] = "Sonia";
StudentsClass["smart"] = "Tra";
StudentsClass["cute"] = "Flora";

The code above creates a blank array and gives it values by assigning values to elements. Each element is given a string in the place of its index number. The value of the string used instead of the index number is something that is meaningful and easily associable with the value of the element of the string.

You can access an associative array in the same way you access a normal array.

StudentsClass["tall"]

If you want to print on the screen the list of the students then you could use:

var StudentsClass = new Array ();
StudentsClass["tall"] = "Dan";
StudentsClass["beautiful"] = "Sonia";
StudentsClass["smart"] = "Tra";
StudentsClass["cute"] = "Flora";

document.write("The tallest student in the class is " + StudentsClass["tall"] + ".<br>");
document.write("The most beautiful student in the class is " + StudentsClass["beautiful"] + ".<br>");
document.write("The smartest student in the class is " + StudentsClass["smart"] + ".<br>");
document.write("The cutest student in the class is " + StudentsClass["cute"] + ".<br>");

Leave a Reply