1

I initialize an array as such:

    imgArray = [];
    imgArray[0,0] = "image1";
    imgArray[1,0] = "image2";
    imgArray[0,1] = "image3";
    imgArray[1,1] = "image4";
    imgArray[0,2] = "image5";
    imgArray[1,2] = "image6";

When I do an alert for imgArray[0,2], I get image6. When I do an alert for imgArray[0,1], I get image4. When I do an alert for imgArray[1,1], I get image4 which is correct.

It appears that the imgArray is totally ignoring my 0 dimension.

7
  • There are no multi-dimensional arrays in JavaScript. Use an array of arrays instead. Commented May 14, 2014 at 14:32
  • 1
    Your problem comes from the comma operator that gets applied to your two indices (Javascript only supports one). See JavaScript multidimensional array. Commented May 14, 2014 at 14:32
  • i think syntex is wrong Commented May 14, 2014 at 14:33
  • @user, on the contrary, the syntax is valid, but imgArray[1, 0] is evaluated as 1; imgArray[0] because of the comma operator. Commented May 14, 2014 at 14:34
  • @FrédéricHamidi this sounds interesting, can you tell us more about what is happening here and how is this syntaxically correct? Commented May 14, 2014 at 14:37

2 Answers 2

5

Multidimensional Arrays in Javascript are written in seperate brackets:

imgArray = [];
imgArray[0] = [];
imgArray[1] = [];
imgArray[0][0] = "image1";
imgArray[1][0] = "image2";
imgArray[0][1] = "image3";
imgArray[1][1] = "image4";
imgArray[0][2] = "image5";
imgArray[1][2] = "image6";
Sign up to request clarification or add additional context in comments.

3 Comments

Tried code change above, get undefined error when trying to access imgArray[1,2]. I have tried every example in all the previous posts about this same topic and they all ignore my left dimension.
Don't try to get imgArray[1,2] (read the answers instead). The correct use is imgArray[1][2]
That worked. After so many hours looking at this BS, I guess I overlooked the details in the comments. Thank you very much.
2
imgArray = [];
imgArray[0] = ["image1", "image2"];

Multidimensional arrays in JavaScript are simply nested arrays.

1 Comment

Tried this imgArray[0]=["image1.jpg","image3.jpg","image5.jpg"]; imgArray[1]=["image2.jpg","images4.jpg","image6.jpg"]; and for imgArray[0,1] I get returned everything in 1,0 which is image2, image4, image6.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.