Multidimensional Arrays in JavaScript

JavaScript FAQ | JavaScript Arrays FAQ  

Question: How do I create a two-dimensional array in JavaScript?

Answer: JavaScript does not have a special syntax for creating multidimensional arrays. A common workaround is to create an array of arrays in nested loops. (This technique is used, for example, to define the game board arrays in several games on this site, such as the JavaScript Tetris game.)

The following code example illustrates the array-of-arrays technique. First, this code creates an array f. Then, in the outer for loop, each element of f is itself initialized as new Array(); thus f becomes an array of arrays. In the inner for loop, all elements f[i][j] in each newly created "inner" array are set to zero.

var iMax = 20;
var jMax = 10;
var f = new Array();

for (i=0;i<iMax;i++) {
 f[i]=new Array();
 for (j=0;j<jMax;j++) {

See also:
Creating an array
Deleting an array element
Are arrays a separate data type?
Array.sort() method

Copyright © 1999-2011,