简体   繁体   中英

Javascript .splice() and .push() error

I have an array array1 and i store its copy in another variable say array2. Now when i try to push a value to array1, the value gets pushed in array2 aswell even though array2 is assigned before pushing value to array1. this happens in .splice() method too.

var array1 = [1,2,3];
var array2 = array1;
array1.push(4);
alert(array1);
alert(array2);

fiddle

You have to clone your first array like this :

var array2 = array1.slice(0);

Updated fiddle

JavaScript has primitive types and reference types.Array is a reference type. Array2 get the reference, so the modification of the array1 will affect the array2 .you can also use this code:

var array1 = [1,2,3];
var array2 = array1.concat();
array2.push(4);
alert(array1);
alert(array2);

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