HTML and CSS Reference
In-Depth Information
EXAMPLE 9.3
<html>
<head><title>The Array Object</title></head>
<body>
<h2>An Array of Numbers</h2>
<script type="text/javascript">
1
var years = new Array(10);
2
for(var i=0; i < years.length; i++ ){
3
years[i]=i + 2000;
4
document.write("years[" + i + "] = "+ years[i]
+ "<br />");
}
</script>
</body>
</html>
EXPLANATION
1
The Array() constructor is called to create a 10-element array called years .
2
The for loop starts with an initial value of i set to 0, which will be the value of the
first index in the array. As long as the value of i is less than the length of the array,
the body of the loop will be executed. Each time through the loop, i is increment-
ed by 1.
3
The array is populated here. Each time through the loop, years[i] is assigned the
value of i + 2000 .
4
The value of the new array element is displayed for each iteration of the loop (see
Figure 9.5).
Figure 9.5 A for loop is used to populate an array: Output from Example 9.3.
Creating and Populating an Array in One Step. When creating an array, you
can populate (assign elements to) it at the same time by passing the value of the ele-
ments as arguments to the Array() constructor. Later on, you can add or delete elements
as you wish. See Example 9.4.
 
Search WWH ::




Custom Search