Figure 9.1. An Array object called color . Index values are in square brackets.
9.2.1 Declaring an Array
Like variables , arrays must be declared before they can be used. The new keyword is used to dynamically create the Array object. It calls the Array object's constructor, Array() , to create a new Array object. The size of the array can be passed as an argument to the constructor, but it is not necessary. Values can also be assigned to the array when it is constructed , but this is not required either. Let's examine some ways to create an array.
The following array is called array_name and its size is not specified.
var array_name = new Array();
In the next example, the size or length of the array is passed as an argument to the Array() constructor. The new array has 100 undefined elements.
var array_name = new Array(100);
And in the next example, the array is given a list of initial values of any data type:
var array_name = new Array("red", "green", "yellow", 1 ,2, 3);
Using the new Constructor
Populating an Array with a for Loop
Populating an array is the process of assigning values to it. In Example 9.2, 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.
Creating and Populating an Array Simultaneously
When creating an array, you can populate (assign elements to) it at the same time by passing the value of the elements as arguments to the Array() constructor. Later on, you can add or delete elements as you wish. See Example 9.3.
An associative array is an array that uses a string as an index value, instead of a number. There is an association between the index and the value stored at that location. The index is often called a key and the value assigned to it, the value . Key/value pairs are a common way of storing and accessing data. In the following array called states , there is an association between the value of the index, the abbreviation for a state (e.g., "CA" ), and the value stored there ”the name of the state (e.g., "California" ). The special for loop can be used to iterate through the elements of an associative array.