Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Using Numeric Arrays

An array is a numbered group of data items that you can treat as a single unit. For example, you might use an array called scores to store several scores for a game. Arrays can contain strings, numbers, objects, or other types of data. Each item in an array is called an element of the array.

Creating a Numeric Array

Unlike most other types of JavaScript variables, you usually need to declare an array before you use it. The following example creates an array with four elements:

scores = new Array(4);

To assign a value to the array, you use an index in brackets. Indexes begin with 0, so the elements of the array in this example would be numbered 0 to 3. These statements assign values to the four elements of the array:

scores[0] = 39;
scores[1] = 40;
scores[2] = 100;
scores[3] = 49;

You can also declare an array and specify values for elements at the same time. This statement creates the same scores array in a single line:

scores = new Array(39,40,100,49);

In JavaScript 1.2 and later, you can also use a shorthand syntax to declare an array and specify its contents. The following statement is an alternate way to create the scores array:

scores = [39,40,100,49];

Understanding Array Length

Like strings, arrays have a length property. This tells you the number of elements in the array. If you specified the length when creating the array, this value becomes the length property's value. For example, these statements would print the number 30:

scores = new Array(30);
document.write(scores.length);

You can declare an array without a specific length, and change the length later by assigning values to elements or changing the length property. For example, these statements create a new array and assign values to two elements:

test = new Array();
test[0]=21;
test[5]=22;

In this example, since the largest index number assigned so far is 5, the array has a length property of 6—remember, elements are numbered starting at zero.

Accessing Array Elements

You can read the contents of an array using the same notation you used when assigning values. For example, the following statements would display the values of the first three elements of the scores array:

scoredisp = "Scores: " + scores[0] + "," + scores[1] + "," + scores[2];
document.write(scoredisp);

Share ThisShare This

Informit Network