javascript tutorial - [Solved-5 Solutions] create a two dimensional array in JavaScript - javascript - java script - javascript array




Problem:

How can I create a two dimensional array in JavaScript?

Solution 1:

var items = [
  [1, 2],
  [3, 4],
  [5, 6]
];
console.log(items[0][0]); // 1
console.log(items);
click below button to copy the code. By JavaScript tutorial team

Solution 2:

var x = new Array(10);
for (var i = 0; i < 10; i++) {
  x[i] = new Array(20);
}
x[5][12] = 3.0;
click below button to copy the code. By JavaScript tutorial team

Solution 3:

function createArray(length) {
    var arr = new Array(length || 0),
        i = length;

    if (arguments.length > 1) {
        var args = Array.prototype.slice.call(arguments, 1);
        while(i--) arr[length-1 - i] = createArray.apply(this, args);
    }

    return arr;
}

createArray();     // [] or new Array()

createArray(2);    // new Array(2)

createArray(3, 2); // [new Array(2),
                   //  new Array(2),
                   //  new Array(2)]
click below button to copy the code. By JavaScript tutorial team

Solution 4:

The following function can be used to construct a 2-d array of fixed dimensions:

function Create2DArray(rows) {
  var arr = [];

  for (var i=0;i<rows;i++) {
     arr[i] = [];
  }

  return arr;
}
click below button to copy the code. By JavaScript tutorial team
  • The number of columns is not really important, because it is not required to specify the size of an array before using it.
  • Then we can just call:
var arr = Create2DArray(100);

arr[50][2] = 5;
arr[70][5] = 7454;
// ...
click below button to copy the code. By JavaScript tutorial team

Solution 5:

var myArray = [[]];
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - create a two dimensional array in JavaScript