views:

63

answers:

1

I have to add some value to an array.

Code for example :

temp[0]=new Array("0","0");
temp[1]=new Array("0","0");
temp[2]=new Array("0","0");
temp[3]=new Array("0","0");
temp[4]=new Array("0","0");

vt=new Array("1","0");
temp.splice(3, 0, vt);
temp.splice(4, 0, vt);

temp[3][1]="R";    

I expect this output :

1 - 0,0
2 - 0,0
3 - 0,0
4 - 1,R
5 - 1,0
6 - 0,0
7 - 0,0

But the actual output is:

1 - 0,0
2 - 0,0
3 - 0,0
4 - 1,R
5 - 1,R
6 - 0,0
7 - 0,0

Any idea? I think it's an indexing problem with splice() function!

+4  A: 

Javascript arrays are objects. When putting an object in an array, you're basically putting a reference to it in the array. You're here putting the same reference in the both places. If you change a reference, it will be reflected in all other references. You need to insert a new and separate object in both places instead so that the references points to a different object.

So instead of

vt=new Array("1","0");
temp.splice(3, 0, vt);
temp.splice(4, 0, vt);

do

temp.splice(3, 0, new Array("1","0"));
temp.splice(4, 0, new Array("1","0"));
BalusC
yeah! this work! tnx dude :)
markzzz
You're welcome. You should then mark this answer accepted :)
BalusC
ok, i've done it :) tnx again!
markzzz