[英]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 to use three-dimensional array in javascript?如何在javascript中使用三维数组?
i mean how to use it like java.我的意思是如何像java一样使用它。
eg: double a = new double[length][length][length];
例如: double a = new double[length][length][length];
how to memorize memory in advance.如何提前记忆记忆。
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!在 Javascript 中,提前实例化变量是没有用的,也没有编译时内存分配这样的东西,因为,嘿,没有编译时! But if you really want to do it, it's not as trivial as in Java:但如果你真的想这样做,它并不像在 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.唯一的一点是,您可以始终确定,只要您保持在 [0, length) 边界内,任何x
、 y
和z
array[x][y][z]
都不会抛出 TypeError。
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 // display for (const i of items) { for (const j of i) { for (const k of j) { console.log('k = ', k) } } }
Similar to rishat's answer, but has different length.类似于 rishat 的答案,但长度不同。
const array1 = Array(2).fill().map(e => Array(4).fill().map(e => Array(3).fill("3").map(e => e))); console.log(JSON.stringify(array1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.