Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript creating multi-dimensional array syntax [duplicate]

Tags:

javascript

Today I've heard that it's possible to create a multi - dimensional array in js using this syntax:

var a = new Array(3,3);
a[2][2] = 2;
alert(a[2][2])

However this doesn't work in opera. Am I wrong somewhere?

like image 330
Dan Avatar asked Feb 10 '11 20:02

Dan


People also ask

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

How do you copy a nested array?

Another method to copy a JavaScript array is using Array. from() , which will also make a shallow copy, as shown in this example: If an object or array contains other objects or arrays, shallow copies will work unexpectedly, because nested objects are not actually cloned.

How do you create a multidimensional array?

Creating Multidimensional Arrays You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.


2 Answers

Yes, you are wrong somewhere. var a = new Array(3,3); means the same as var a = [3,3];. It creates an array with two members: the Number 3 and the Number 3 again.

The array constructor is one of the worst parts of the JavaScript language design. Given a single value, it determines the length of the array. Given multiple values, it uses them to initialise the array.

Always use the var a = []; syntax. It is consistent (as well as being shorter and easier to read).

There is no short-cut syntax for creating an array of arrays. You have to construct each one separately.

var a = [ 
          [1,2,3],
          [4,5,6],
          [7,8,9]
         ];
like image 75
Quentin Avatar answered Nov 14 '22 23:11

Quentin


The code you posted makes an array consisting of two integers. You're then trying to treat an integer as an array.

mv = new Array();
mv[0] = new Array();
mv[0][0] = "value1-1";
mv[0][1] = "value1-2";

mv[1] = new Array();
mv[1][0] = "value2-1";
mv[1][1] = "value2-2";

There is no way to directly instantiate a multidimensional array.

like image 30
Chris Baker Avatar answered Nov 15 '22 00:11

Chris Baker