HTML and CSS Reference
In-Depth Information
EXAMPLE
9.9
<html>
<head><title>Associative Array</title></head>
<body>
<p style="font-size:150%">
<script type="text/javascript">
1
var student=new Array();
2
student["Name"]="John Doe"; //
one key, one value
3
student["Courses"]=new Array("Math","English", "PE");
4
student["Phones"]=new Array("415-333-1234","530-345-5432");
5
document.write("The student's name is " +
student["Name"] +
".<br />");
6
document.write("His courses are " +
student["Courses"]
+
".<br />");
7
document.write("His favorite course is "+
student["Courses"][2]
+ ".<br />");
8
document.write("His cell phone number is " +
student["Phones"][0]
+ ".<br />");
</script>
</p>
</body>
</html>
EXPLANATION
1
A new array object called
student
is instantiated.
2
An index or key in the
student
array is a string of text,
“Name”
assigned a single
value,
“John Doe”
. Now there is an association between the index and the value.
3
The index key is
“Courses”
. The student takes more than one course. A new Array
is created with the values of the courses assigned to the key, an array with a nested
array.
4
The index key is
“Phones”
. The student has two phones. A new Array is created
with two phone numbers assigned to the key, an array with a nested array.
5
To get the name of the student, the
“Name”
is used as an index, also called the key.
6
To get a list of all the courses, the key/index in the array is
“Courses”
.
7
To get one of the courses out of the list, two index values are needed, one to key
into the courses and one to select a specific course. Because array index values
start at 0, student
[“Courses”][2]
gets the third course,
“PE”
.
8
Again two index values are need to get one of the phone numbers.
stu-
dent["Phones"][0]
gets the value of the first phone. The output is shown in Figure
9.12.