Arrays let you store several pieces of data in the same variable. Usually the pieces have a common theme. This can save you creating a heap of variables all with similar names. This is how they work:
var month_totals = new Array(12);
month_totals[3] = 1999.95;
month_totals[4] = 'No sales';
var a=4;
document.write(month_totals[a]);
document.write(month_totals.length);
document.write(month_totals);
var days = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
The variables totals and days are made into arrays by the as-yet cryptic code 'new Array(…)
'. This does two things. First, the number of items in the array is decided, and stored in a hidden place called 'length
'. In line 1, it's set explicitly to 12. Second, space for some variables (also called array elements) is created, which is equal to the size of the array. Line 2 shows one of those items storing a value. '[3]
' means the array element with element index 3. Array elements are counted from 0
(zero), not one, so a three element array called fred has elements fred[0], fred[1] and fred[2]. As line 2 and 3 show, array elements, can contain different types of data: 'month_totals[3] = 1999.95
' is an an array variable of the Number type, whereas the third line, 'month_totals[4] = 'No sales'
' is a String type..
Accessing array elements is easy. The first two document.write()
lines display 'No sales' and '12'. The last line shows a shorthand way of creating an Array and setting all its elements at the same time.
Arrays in JavaScript are closely tied to objects, which are discussed further on. In particular, the array indices are not restricted to numbers because of their object-like status. Arrays can also expand in size (in number of elements) just by storing a value in an array element whose index is bigger than any that exists so far. So arrays are quite flexible compared to equivalent concepts in other languages.
The third document.write() above only needs to report that the variable printed is an object to match ECMAScript. However, Netscape Navigator will print out all the array elements, comma-separated, which is very handy. Navigator 2.02 doesn't know how to do 'new Array', and neither does Internet Explorer 3.02 with JScript 1.0, but it can be simulated with objects—see that section.
One of the things you can store in an array element is another array. An array of arrays can be treated like a multidimensional array, which has a number of uses, particularly in mathematics and graphics. This example creates a two-dimensional array of size two-by-two, and fills it with the values that make up an 'identity matrix'.
var matrix = new Array(2);
matrix[0] = new Array(2);
matrix[1] = new Array(2);
matrix[0][0] = 1;
matrix[1][0] = 0;
matrix[0][1] = 0;
matrix[1][1] = 1;