HTML and CSS Reference
In-Depth Information
EXAMPLE 9.2
<html>
<head><title>The Literal Way</title>
<h2>An Array of Pets</h2>
<script type="text/javascript">
1
var pet = [ "Fido", "Slinky", "Tweetie","Wanda" ];
</script>
</head>
<body bgcolor="lavender">
<font size="+2">
<script type="text/javascript">
2
for(var i in pet){
3
document.write("pet[" + i + "] "+ pet[i] + "<br />");
}
</script>
</font>
</body>
</html>
EXPLANATION
1
The variable pet is assigned a list enclosed in square brackets. This is called an ar-
ray literal.
2
The special for loop is used to access each of the elements in the pet array where
this example represents the index value, whether a number or a string.
3
Each of the elements of the pet array is displayed in the browser (see Figure 9.4).
Figure 9.4 An array literal and its output.
Populating an Array with a for Loop. Populating an array is the process of assign-
ing values to it. In Example 9.3, the for loop is used to fill an array. The initial value of
the index starts at zero; the looping will continue as long as the value of the index is less
than the final size of the array.
 
Search WWH ::




Custom Search