0

When I first declare an array called emptyline like this:

var emptyline=[];
for (var i=0;i<10;i++)
    emptyline.push(-1);

Then I make a 2D array using it:

var c=[];
    for (var i=0;i<20;i++) c.push(emptyline);

And finally I set an element like this:

c[1][6]=3;

It looks like this when I type c in the Chrome/Safari Console:

[
Array[10]
//...
4: -1
5: 0
6: 3
7: -1
//...
, 
Array[10]
//...
4: -1
5: 0
6: 3
7: -1
// etc.
]

In some cases index 5 is 0, in some it is -1. Why does this happen and how can I fix it?

gskartwii
  • 389
  • 2
  • 7
  • 18
  • 1
    `c.push(emptyline)` doesn't do what you think it does. You push a reference to `emptyline` to each index of `c`. – Teemu May 29 '14 at 13:24
  • possible duplicate of http://stackoverflow.com/questions/9190518/how-do-i-pass-the-value-instead-of-the-refererence-of-an-array – KnightHawk May 29 '14 at 13:35

1 Answers1

0

This is the solution:

First use this code:

Array.prototype.clone=function() {
    return this.slice(0);
}

Then use the following code instead of the 2nd code:

var c=[];
for (var i=0;i<20;i++) c.push(emptyline.clone());

Thanks, Teemu & David Walsh!

gskartwii
  • 389
  • 2
  • 7
  • 18
  • 1
    Why not just `c.push(emptyline.slice());`? Notice also, that this works only when `emptyline` contains only primitives, objects are still copied by reference. – Teemu May 29 '14 at 13:35