Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a two dimensional array in JavaScript?

I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.

  1. How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)

  2. How would I access its members? (myArray[0][1] or myArray[0,1]?)

like image 655
Diego Avatar asked Jun 08 '09 18:06

Diego


People also ask

Can you have a 2D array in JavaScript?

Assuming a somewhat pedantic definition, it is technically impossible to create a 2d array in javascript. But you can create an array of arrays, which is tantamount to the same. FYI... when you fill an array with more arrays using var arr2D = new Array(5).

What is two-dimensional array JavaScript?

The two-dimensional array is a collection of items which share a common name and they are organized as a matrix in the form of rows and columns. The two-dimensional array is an array of arrays, so we create an array of one-dimensional array objects.


2 Answers

var items = [    [1, 2],    [3, 4],    [5, 6]  ];  console.log(items[0][0]); // 1  console.log(items[0][1]); // 2  console.log(items[1][0]); // 3  console.log(items[1][1]); // 4  console.log(items);
like image 133
Ballsacian1 Avatar answered Sep 28 '22 05:09

Ballsacian1


You simply make each item within the array an array.

var x = new Array(10);    for (var i = 0; i < x.length; i++) {    x[i] = new Array(3);  }    console.log(x);
like image 35
Sufian Avatar answered Sep 28 '22 05:09

Sufian