HTML and CSS Reference

In-Depth Information

Problem Solving: Using Multidimensional Arrays

Many database applications need to store data in a rectangular format known as a
matrix
,

in which the values are arranged in a rectangular grid. The following is an example of a

matrix laid out in a grid of three rows and four columns:

4 15

8

2

1

3

18 6

3

7

10 4

The rows and columns in a matrix form the basis for indices. For example, the value 18

from this matrix is referenced using the index pair (2, 3) because that value appears at the

intersection of the second row and third column.

Although matrices are commonly used in databases (where each row might represent an

individual and each column a characteristic of that individual), JavaScript does not support

matrices. However, you can mimic the behavior of matrices in JavaScript by nesting one

array within another in a structure called a
multidimensional array
. For example, the fol-

lowing code creates the array
mArray
, which contains a collection of nested arrays:

var mArray =

[

[4, 15, 8, 2],

[1, 3, 18, 6],

[3, 7, 10, 4]

];

Note that the values of this array match the values of the matrix shown above. In this case,

the first nested array matches the first row of the matrix, the second array matches the

second row, and the third array matches the third row. The values of the nested arrays are

matched with each of the four columns.

Values within a multidimensional array are referenced by the expression

array
[
x
][
y
]

where
x
contains the index of the outer array (the row) and
y
contains the index of the

nested array (the column). Thus, the expression

mArray[1][2]

returns the value 18 from the matrix's second row and third column (remember that indices

start with 0, not 1). The number of rows in a multidimensional array is given by the
length

property. The number of columns can be determined by retrieving the
length
property for

the first row of the table. For example, the expression

mArray[0].length

would return a value of 3 for the three columns in mArray. Note that this approach pre-

sumes that every row has the same number of columns.

You can continue to nest arrays in this fashion to create matrices of even higher

dimension.

Reversing an Array

Arrays are associated with a collection of methods that allow you to change their con-

tents, order, and size. You also can use these methods to combine different arrays into

a single array and to convert arrays into text strings. Although you will not need to use

these methods with the calendar() function, you'll examine them for future projects.

By default, items are placed in an array either in the order in which they are defined,

or explicitly by index number. JavaScript supports two methods for changing the order