1

It's really strange, I'm modifying one of the arrays and the other one gets modified! I found no way of making it work other than typing two times the array. What can I do?

function test(a,b,c,d)
{
    this.a=a;
    this.b=b;
    this.c=c;
    this.d=d;
}

var data0=data=[[1,2,3,4],[5,6,7,8]];

function construct(constructor,args)
{
    function F(){return constructor.apply(this,args);}
    F.prototype=constructor.prototype;
    return new F();
}

for(var i=0,l=data.length;i<l;i++)
{
    data[i]=construct(test,data[i]);
}

console.log(data0);

http://jsfiddle.net/mageek/3GNMC/2/

Alexandre Khoury
  • 3,896
  • 5
  • 37
  • 58
  • data0 and data are the same array. Use `data0 = data.slice(0);` to clone – mishik Jun 29 '13 at 09:15
  • You are not creating separate copies of your array, instead creating separate references to the same array. Search the site for how to clone/copy an array and you will find your answer. – Derek Henderson Jun 29 '13 at 09:16

2 Answers2

2

You are referencing the same items:

var data0=data=[[1,2,3,4],[5,6,7,8]];

(and as a side note - here data ends up on the global object as it isn't really declared, only data0 is)

If you want to generate two different arrays with identical items you can do this:

var data0 =[[1,2,3,4],[5,6,7,8]];
var data = [];

data = data.concat(data0);

or

 data = data0.slice(0);
1

JavaScript will not copy arrays upon data0=data assignment, instead it will point both variables to the same object in memory. You need to actually clone the array fully, for example:

var data0 = data.slice(0);
mishik
  • 9,973
  • 9
  • 45
  • 67