
| What happens if the elements of an Array
object are arrays themselves? The results is an Array of Arrays, also
called a 2-dimensional array. This
nesting of Arrays within arrays can go on for three, four, or more
dimensions.
A 2-dimensional Array could, for example, be used to store sales statistics for 3 regions in 4 different Months:
The month and region titles are assigned to 2 Arrays -- monthName and regionName. The four Arrays -- Jan, Feb, Mar, and Apr -- each contain 3 Sales Numbers, one for each Region. Finally, we combine all four into a single Array called sales.
This begins by declaring two variables, m and r. Then we write the word Month in the first cell of the table, followed by the 3 Region names. A for loop is used to loop around and display the contents of the regionName Array, one element in each cell of the top row.
This uses the nested for loops. The outer loop uses the variable m to step through all the months, writing the month names -- stored in the monthName Array -- in the first column. The inner loop uses the variable r to enter the data from the sales array into the appropriate rows. document.write("<TD>" + sales[m][r] + "</TD>"); // 2-dimensional array This contains the expression sales[m][r], which represents the m'th element of the r'th element of sales. The double index ([m][r]) is how JavaScript accesses an element of an element. For example, where m = 0 and r = 2, JavaScript looks at the 1st Array stored in sales (the Jan Array), then looks at the 3rd element stored within that Array (180).
|