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

. Then, in the outer
loop, each element of
is itself initialized as
new Array()
; thus
becomes an array of arrays. In the inner
loop, all elements
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 © 1996-2018,