Javascript creating a multidimensional syntax array

Today I heard that you can create a multidimensional array in js using this syntax:

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

However, this does not work in opera. Am I mistaken somewhere?

+5
source share
3 answers

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

Array constructor is one of the worst parts of JavaScript design. Given a single value, it determines the length of the array. Given several values, it uses them to initialize the array.

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

. .

var a = [ 
          [1,2,3],
          [4,5,6],
          [7,8,9]
         ];
+7

, . .

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";

.

+2

you want to create an array of arrays, but you create an array with two elements:

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

if you want to create a multidimensional array, you need to think about an array of arrays.
thus, a two-dimensional array (or matrix) will be defined as:

var a = [[],[]];//or var a = new Array([],[]);
//or if you want to initialize the matrix : 
var b = [
    [1,2],
    [3,4]
];
0
source

All Articles