1

I am trying to set a multi-dimensional array in JavaScript but it returns the last entry for all data. I am expecting the alert to return 444 but it returns 555.

Any ideas?

function test() {
    var arr = [,];
    arr[1]="qtest0";
    arr[1,0]=444;
    arr[2,0]=555;
    arr[2]="qtest1";
    alert(arr[1]);
    alert(arr[1,0]);
}
6
  • 2
    What are you expecting arr[1,0] and the others like it to do? You're basically only accessing the index after the comma. The index before is ignored. Commented Jul 5, 2015 at 3:29
  • 2
    ...JavaScript doesn't have true multidimensional arrays. You can create nested "arrays of arrays", but they need to be created manually. Commented Jul 5, 2015 at 3:30
  • 1
    This is multi dimen array [[1,2],[3,4],[[5,6],[7,8]]] yours is I dont know where you learned that from array Commented Jul 5, 2015 at 3:42
  • @Dummy - Your example isn't a multidimensional array, it is an array of arrays. Similar, but not quite the same thing. Other languages allow multidimensional arrays with a syntax similar to the OP's. Commented Jul 5, 2015 at 3:48
  • 1
    @nnnnnn multi dimen arrays are arrays of arrays, what's your point? I have never seen any language that allows for the creation of multi dimen arrays using the OP's syntax Commented Jul 5, 2015 at 3:50

1 Answer 1

6

This statement:

var arr = [,];

Does not create a multidimensional array. It creates a sparse array with one empty slot in it. And this statement:

arr[1,0]=444;

Does not assign to a two-dimensional array index. Rather, the expression 1,0 simply evaluates to 0 (this is how the somewhat obscure comma operator works). So arr[1,0] is exactly the same as arr[0].

Javascript does not natively support multidimensional arrays. Rather, you should have an array whose elements are themselves arrays:

var arr = [];
arr[1] = [];
arr[1][0] = 444;

For more information on multidimensional arrays, see this question.

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

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.