简体   繁体   中英

javascript splice() indexing problem

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!

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM