0

I have created this multidimensional array in javascript.

var arr = [];
arr[0] = [];
arr[0][0] = [];
arr[0][0][0] = [];
arr[0][0][0][0] = []; 

and assigning values to the using this code

arr[0] = 1;
arr[0][0] = 2;
arr[0][0][0] = 3;
arr[0][0][0][0] = 4;
arr[0][0][0][0][0] = 5;
alert("arr ==> " + arr);

But it gives output as only 1, but the desired output is 1,2,3,4,5

When I do this alert(arr[0][0]); the desired output is 2 but it gives undefined.

Thanks for helping.

4
  • 1
    JavaScript doesn't have multi-dimentional arrays in the manner you're thinking. It has nested arrays just like you can have nested objects (since arrays are just objects). Commented Feb 6, 2013 at 6:27
  • Even if your "multi-dimensional array" was filled the way you intended, it would never print 1,2,3,4,5. That being said, JavaScript is not PHP. Chances are you are using the wrong data structure. Commented Feb 6, 2013 at 6:28
  • @Tomalak Thanks for replying. Can you tell me how can I set the data in my desired manner. Commented Feb 6, 2013 at 6:30
  • As has been said, there are no true multi-dimensional arrays in JavaScript, only nested arrays. Can you tell me what you want to do? ("I'm trying to use a multi-dimensional array" is not an answer.) Commented Feb 6, 2013 at 6:34

2 Answers 2

4

You're overwriting your values:

arr[0] = [];
...
arr[0] = 1; // this also blows away arr[0][0], arr[0][0][0], etc

so...

arr[0][0] = 1;
==
1[0] = 1;

What exactly are you trying to do?

Sign up to request clarification or add additional context in comments.

2 Comments

I want to set the values at zero position upto 5 dimension.
You can't have arr[0] be both zero and an array. What's the purpose of this?
1
var arr = [];
arr[4] = [];

arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

alert("arr ==> " + arr );

I hope this will solve your problem.

Alerts as

arr ==> 1,2,3,4,5

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.