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?
Answer
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]
];
No comments:
Post a Comment