Reputation: 5980
I was reading a book about Javascript and saw this line;
JavaScript does not support true multidimensional arrays, but you can approximate them with arrays of arrays.
What's the difference?
Upvotes: 16
Views: 954
Reputation: 54999
The author seems to assume that a “true” multidimensional array is one where all elements:
Are arrays;
Are stored by value, not by reference; and
Have the same length.
JavaScript arrays may contain other arrays, but not by value, only by reference. That is, the elements of each row may be contiguous in memory, but the rows themselves may not. Further, there is no way to statically indicate that all of the inner arrays must have the same length, because JavaScript is dynamically typed.
But an array of arrays is precisely what you ought to use to represent a multidimensional array in JavaScript, and the details of the internal representation are probably not relevant to you when you’re just learning the language.
Upvotes: 2
Reputation: 19027
Although the JavaScript specification (3.0) does not make mention of multi-dimensional arrays, they are in fact possible. Multi-dimensional arrays can be represented by arrays of arrays. See.
For example.
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // Would alert 1
One dimensional array in Javascript.
var a = [0, 1, 2, 3];
a[[2]] === a[2]; // this is true
2 == [2] //true
// Even complex
2 == [[[2]]] //true
// And even more
var a = { "xyz" : 1 };
a[[[["xyz"]]]] === a["xyz"]; //true
Upvotes: 1
Reputation: 230356
(a visual explanation that complements an excellent answer of @recursive)
In some languages (C#) there are both. The difference is in "shape" of such arrays.
int[3, 4] // true two-dimensional array
// it will "look" like this, rectangular shape
[[0, 0, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]]
But when you define an array of arrays, it can easily (especially in javascript) look like this. It's called a jagged array.
[[0, 0]
[0, 0, 0, 0, 0, 0]
[0, 0, 0]]
Upvotes: 3
Reputation: 490303
There is nothing in JavaScript like...
var arr = new Array[5][3]; /* Some weird JS/C-like thing for demonstration */
...with enforced lengths. Like a matrix.
However, you can build an Array
of which its members are all Array
s of a fixed length. If one of the sub Array
s were to have a different length, it would be a jagged Array
.
Upvotes: 2
Reputation: 86084
A true multi-dimensional array must be indexed with multiple indices. An array of arrays can be indexed with a single index, which will return another array. A true multi-dimensional array stores all its data contiguously. An array of arrays stores all its constituent arrays arbitrarily scattered around. This can improve iteration performance because of cache effects for true arrays.
Upvotes: 17