Cery Cery - 1 month ago 27
Javascript Question

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' of undefined(…)


How can i use three-dimensional array in javascript?

i mean how to use it like java.

eg:
double a = new double[length][length][length];


how to memorize memory in advance.

Answer

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;
const range = 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.