Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

three-dimensional array in javascript

Tags:

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?

i mean how to use it like java.
eg: double a = new double[length][length][length];

how to memorize memory in advance.

like image 703
Cery Avatar asked Aug 03 '26 13:08

Cery


2 Answers

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.

like image 66
rishat Avatar answered Aug 06 '26 10:08

rishat


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)
    }
  }
}
like image 42
Alongkorn Avatar answered Aug 06 '26 10:08

Alongkorn