Referencing Array Elements in JavaScript
Since JavaScript arrays are de facto a container for multiple variables, you need an easy way to reference these variables. By default, JavaScript arrays are numerically indexed, starting with a zero. This is important: the first array element is element zero; element one is the second element.
In another tutorial, we will show you how to use a more friendly way to reference array elements, with associative arrays.
Referencing One-dimensional Array Elements
To reference standard array elements, simply use the array variable name, followed by the numerical index of the element enclosed in square brackets.
// Declare a one-dimensional JavaScript array
var arlene = new Array("I", "learn", "JavaScript");
alert( arlene[2] );
The script above creates an array, and assigns it three string elements. The last line of our script sends the third array element (at index 2) to the alert() method, and produces the following result:
Array[2]
always refers to the third element of an array: this is because array indexes are zero-based, and the first array element actually is Array[0]
…
This is very confusing for the beginner programmer, and will be the source of many logical errors in your scripts. This is normal, but make sure you keep it in mind whenever dealing with arrays.
Referencing Multidimensional Array Elements
Referencing elements in multidimensional arrays works much the same way; you only have to remember that the leftmost index points to the outermost array.
// Declare a multidimensional array of 2x3 dimension
var arlene = [ ["A1","A2"], ["B1","B2"], ["C1","C2"] ];
alert( arlene[0][0] +" ... "+ arlene[0][1] );
The alert() method in the script above calls the first and second element of the first array element (read it once more, slowly). Here is the result:
To display the first and second element of the second "inner array", use the following script:
// Re-using the multidimensional array we declared earlier...
alert( arlene[1][0] +" ... "+ arlene[1][1] );
The alert returns what would correspond to the second row in a tabular representation of our array:
...In other words, the content of the second row's first and second cell