JavaScript tutorial:
JavaScript arrays        

Array indexing

Arrays in JavaScript are incredibly flexible. The first element in an array has the index 0, and the length of an array is handled automatically. You can place elements at any index in an array at any time. Traversing the elements of an array is in essence the same as traversing the properties of an object.

Retrieving array elements

The simplest way to address an array is by specifying the index inside the [] brackets. The index has to be a whole nonnegative number (or an expression). The index of the first element is 0 (the same as in C/C++, C#, or Java; for VB and some other languages the index of the first element is 1).

// Define an array
days = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

// Get the third element
thirdDay = days[2];
document.write(thirdDay);

// Since thirdDay is also an array (of letters), get the fourth letter
fourthLetter = thirdDay[3];
document.write(fourthLetter);

To run the code, paste it into JavaScript Editor, and click the Execute button.

The code below creates and initializes the most familiar form of an array. Each element of this array is addressed using its element number; in this case 0, 1, or 2. Using the for...in statement, the array can be iterated starting at 0 and ending at 2. For example:

myArray = new Array("Athens", "Belgrade", "Cairo");
for (key in myArray)
document.write("Element value is " + myArray[key]);

To run the code, paste it into JavaScript Editor, and click the Execute button.

The following code creates and initializes an associative array containing three elements:

myArray = {"a" : "Athens", "b" : "Belgrade", "c" : "Cairo" };
for (key in myArray)
document.write("For the key " + key
+ " element value is " + myArray[key]);

To run the code, paste it into JavaScript Editor, and click the Execute button.

This is associative addressing of the array, that is, addressing by means of fully arbitrary strings. Objects in JavaScript are actually associative arrays. Although you can (and frequently do) use the "dot" style of addressing, you are not by any means required to. Because the members of any JavaScript object can be accessed using array notation, a JavaScript object can be used as an associative array.

In this array, elements are addressed using the key strings("a", "b", or "c") instead of an array element number (0, 1, or 2). In the example above, myArray["c"] returns "Cairo". This allows you to create and use arrays with more intuitive addressing schemes. The same for...in statement code shown above can be used to iterate this array as well.

Next