0

I am new in JavaScript, I would like to initialize a 2D array and change one of the character. However, when I change one of the array value e.g. abc[1,1], the whole column changed. I would like to ask why and how to prevent it? i have tried to use .slice to make a copy, but seem dont work

My prefered result
- - -
- 1 -
- - -

The actual ans:
- 1 -
- 1 -
- 1 -


//My code:
var abc = new Array(3,3)
for(var i =0; i<3;i++)   
   for(var j =0; j<3;j++)
      abc[i,j]="-"

abc[1,1] ="1"

for(var i =0; i<3;i++){
    for(var j =0; j<3;j++)
        document.writeln(abc[i,j]+" ")
    document.writeln("<br \>")
}
Question-er XDD
  • 640
  • 3
  • 12
  • 27
  • 2
    There is no multi-dimensional array access notation in javascript. Everything before the comma is simply ignored (see [here](http://stackoverflow.com/a/20645300/1048572) for more info). You need to use nested arrays, and access them like `abc[i][j]`. – Bergi Apr 26 '15 at 22:08

1 Answers1

2

The comma operator evaluates both expressions and returns the last one. So i,j returns j.

In fact, you are using a 1D array, not a 2D one.

The proper way is:

var abc = Array(3);
for(var i=0; i<3; ++i) {
   abc[i] = Array(3); 
   for(var j=0; j<3; ++j)
      abc[i][j] = "-"
}
abc[1][1] = "1";
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • +1, though it is recommended usually not to use the `Array` constructor (and its length argument) at all, but just array literals like `[]`. – Bergi Apr 26 '15 at 22:12