HTML and CSS Reference
In-Depth Information
EXAMPLE
9.6
<html>
<head><title>Associative Arrays</title></head>
<body>
<h2>An Array Indexed by Strings</h2>
1
<script type="text/javascript">
2
var states = new Array();
3
states["CA"] = "California";
states["ME"] = "Maine";
states["MT"] = "Montana";
4
for( var i in states )
{
document.write("The index is:<em> "+ i );
document.write(".</em> The value is: <em>" + states[i]
+ ".</em><br />");
}
</script>
</body>
</html>
EXPLANATION
1
The JavaScript program starts here.
2
The
Array()
constructor is called and returns a new
Array
object called
states
.
3
The index into the array element is a string of text, “CA”. The value assigned is
“California”
. Now there is an association between the index and the value.
4
The special
for
loop is used to iterate through the
Array
object. The variable,
i
,
represents the index value of the array, and
states[i]
represents the value found
there. It reads: For each index value in the array called
states
, get the value asso-
ciated with it (see Figure 9.8).
Figure 9.8
An associative array.
Bracket vs. Dot Notation.
This is an important note: any object, not just the
Array
object, can use the square bracket notation to reference it's properties. The following two
expressions are interchangeable:
cat.color = "black";
cat["color"] = "black";