How do I declare two dimensional arrays in javascript?
In javascript:
var Matrix = function (rows, columns) {
this.rows = rows;
this.columns = columns;
this.myarray = new Array(this.rows);
for (var i=0; i < this.columns; i +=1) {
this.myarray[i]=new Array(this.rows)
}
return this.myarray;
}
var m = new Matrix(2,2);
m; // [[undefined, undefined], [undefined, undefined]];
var m2 = new Matrix(3,3);
m2; // [[undefined, undefined, undefined], [undefined, undefined, undefined], [undefined, undefined, undefined]]
A quick example of what @SLaks is referring to with jagged arrays. You basically put an array in an array. The below example shows one way to make an array thats 100x100.
var arr = [];
for(var x = 0; x < 100; x++){
arr[x] = [];
for(var y = 0; y < 100; y++){
arr[x][y] = x*y;
}
}
console.log(arr[10][11]);
Live Demo
This method is very flexible for instance arr[4]
could have an array indexed to 10, and arr[5]
could have an array with 1 value, or be even be a completely different type such as a string or number.
Unlike C#, Javascript does not support multi-dimensional arrays.
Instead, you can use nested ("jagged") arrays.
A nested 3x3 array (of undefined
):
var arr = new Array(3);
for (var i = 0; i < arr.length; ++i) {
arr[i] = new Array(3);
}
console.log(arr);
modle13 commented that you're restricted to a fixed size sub-array, so here's one quick tweak to get around that:
var nestedSizes = [3,5,1,4];
var arr = new Array(nestedSizes.length);
for (var i = 0; i < arr.length; ++i) {
arr[i] = new Array(nestedSizes[i]);
}
console.log(arr);