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

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. Commented Sep 14, 2017 at 5: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. Commented Sep 14, 2017 at 5:07
  • @Teemu : Can you show me how to do it? Commented Sep 14, 2017 at 5:09
  • I'm sure you can create the nested loops needed for task without any example. Commented Sep 14, 2017 at 5:10

2 Answers 2

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";
Sign up to request clarification or add additional context in comments.

4 Comments

sorry i meant java script, fixing
Technically there is a compile-time, since it's a JIT compiled language. 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).
@Legman why there is no semi colon at the line 3? myArr[0][0] = new Array()
Typo, it has been fixed
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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.