JavaScript: Multi-dimensional Array

by Yang Yang on February 3, 2009

In JavaScript, you initiate an array of 3 elements by:

var myArray = new Array(3);

Or:

var myArray = ['', '', ''];

And then to populate them with some values, you need:

for (var i = 0; i < 3; i++) {
	myArray[i] = i;
}

This is pretty much a single dimensional array. To create a multi-dimensional array such as a 2 dimensional one, you need to add one more dimension, initiating yet another array for each of the 1st-dimension elements:

var myArray = new Array(3);

for (var i = 0; i < 3; i++) {
	myArray[i] = new Array(3);
	for (var j = 0; j < 3; j++) {
		myArray[i][j] = '';
	}
}

A more straightforward approach is to directly assign values to multi-dimensional array variables:

myArray[0][0] = '';
myArray[0][1] = '';
myArray[0][2] = '';
myArray[1][0] = '';
myArray[1][1] = '';
myArray[1][2] = '';
myArray[2][0] = '';
myArray[2][1] = '';
myArray[2][2] = '';
Subscribe to Kavoir: blog feed

You should also read:

{ 17 comments… read them below or add one }