1

I have tried to create 3 dimensional array and assigning value to it, base on the answer here creating and parsing a 3D array in javascript? .

var myArr = new Array(new Array(new Array()));

myArr[0][0][0] = "1";
myArr[0][0][1] = "2";
myArr[0][1][0] = "2";
myArr[0][1][1] = "2";
myArr[0][2][0] = "3";
myArr[0][2][1] = "4";

but I get this

Uncaught Typeerror: Cannot set propterty '0' of undefined".

Need some help.

Thank you

Wasif Ali
  • 886
  • 1
  • 13
  • 29
belldiaz
  • 11
  • 1
  • 4
  • The problem here is that `var myArr = new Array(new Array(new Array()));` translates to `myArr[0][0] = [ ]` meaning that when trying to access `myArr[0][1]` you get an undefined object, since in fact, you never created an array at that index. – mnewelski Sep 14 '17 at 05:07
  • 2
    There are no multidimensional arrays in JS, you can only emulate them with nested arrays. This means, that you've to define every member separately as a subarray. – Teemu Sep 14 '17 at 05:07
  • @Teemu : Can you show me how to do it? – belldiaz Sep 14 '17 at 05:09
  • I'm sure you can create the nested loops needed for task without any example. – Teemu Sep 14 '17 at 05:10

2 Answers2

1

There are no initiating variables in advance in javascript and the compilation step simply hoists top-level variable and function definitions, and in ES6, does static importing and exporting (though that's not yet natively supported)[Patrick Roberts]. One additional option is

var myArr = new Array();
myArr[0] = new Array();
myArr[0][0] = new Array();
myArr[0][0][0] = "1";
myArr[0][0][1] = "2";
myArr[0][1] = new Array();
myArr[0][1][0] = "2";
myArr[0][1][1] = "2";
myArr[0][2] = new Array();
myArr[0][2][0] = "3";
myArr[0][2][1] = "4";
Lucas Hendren
  • 2,786
  • 2
  • 18
  • 33
0

You can do like this (but creating 3d array in javascript is more completed stuff. Please consider changing your approach to handle data):

var myArr = new Array();
myArr[0] = new Array();
myArr[0][0] = new Array();
myArr[0][0][0] = "1";
myArr[0][0][1] = "2";
myArr[0][1] = new Array();
myArr[0][1][0] = "2";
myArr[0][1][1] = "2";
myArr[0][2] = new Array();
myArr[0][2][0] = "3";
myArr[0][2][1] = "4";

console.log(myArr[0][2][0]);
Jigar Shah
  • 6,143
  • 2
  • 28
  • 41