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]);
}
Michael Geary
  • 28,450
  • 9
  • 65
  • 75
  • 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. –  Jul 05 '15 at 03:29
  • 2
    ...JavaScript doesn't have true multidimensional arrays. You can create nested "arrays of arrays", but they need to be created manually. –  Jul 05 '15 at 03: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 – Trash Can Jul 05 '15 at 03: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. – nnnnnn Jul 05 '15 at 03: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 – Trash Can Jul 05 '15 at 03:50
  • @Dummy - No, a multidimensional array is a single array object that has multiple dimensions. Pascal is the first language that comes to mind that supports true multidimensional arrays (not with the OP's syntax, but it has them), and there are others - I think VB has multidimensional array syntax more like the OP's. As Squint said above, JavaScript doesn't have them. Your example is six separate array objects, some of which contain references to the others. For practical purposes they achieve pretty much the same thing, but technically they are different. – nnnnnn Jul 05 '15 at 03:53

1 Answers1

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.

Community
  • 1
  • 1
Thom Smith
  • 13,916
  • 6
  • 45
  • 91