Three-dimensional Array In Javascript
var a = new Array(); var b = [1,2,3,4,5,6,7]; for(i in b){a[i] = new Array(new Array());} a[0][1][2] = Math.random();// error:VM205:1 Uncaught TypeError: Cannot set property '2' o
Solution 1:
In Javascript, there's no use in instantiating variables in advance, and there is no such thing as compile-time memory allocation because, hey, there's no compile time! But if you really want to do it, it's not as trivial as in Java:
const length = 7;
constrange = new Array(length).fill();
const array = range.map(e => range.map(e => range.map(e => e)));
console.log(JSON.stringify(array)); // -> "[[[null,null,null],[null,null,null],[null,null,null]],[[null,null,null],[null,null,null],[null,null,null]],[[null,null,null],[null,null,null],[null,null,null]]]"
The only point in it is that you can be always sure that, as long as you stay in [0, length) boundaries, array[x][y][z]
for any x
, y
and z
will not throw a TypeError.
Solution 2:
you can do like this
const items = [[[]]] // init 3d array// assign values
items[0][0][0] = 0
items[0][0][1] = 1
items[0][0][2] = 2// displayfor (const i of items) {
for (const j of i) {
for (const k of j) {
console.log('k = ', k)
}
}
}
Solution 3:
Similar to rishat's answer, but has different length.
const array1 = Array(2).fill().map(e =>Array(4).fill().map(e =>Array(3).fill("3").map(e => e)));
console.log(JSON.stringify(array1));
Post a Comment for "Three-dimensional Array In Javascript"