JavaScript数组复制详解
前面的话
前面的博文中介绍了对象拷贝,本文将详细介绍数组复制
push
functioncopyArray(arr){
varresult=[];
for(vari=0;i<arr.length;i++){
result.push(arr[i]);
}
returnresult;
}
varobj1=[1,2,3];
varobj2=copyArray(obj1);
console.log(obj1);//[1,2,3]
console.log(obj2);//[1,2,3]
obj2.push(4);
console.log(obj1);//[1,2,3]
console.log(obj2);//[1,2,3,4]
join
使用该方法的缺点是数组中的项全部变成了字符串形式
functioncopyArray(arr){
varresult=[];
result=arr.join().split(',');
returnresult;
}
varobj1=[1,2,3];
varobj2=copyArray(obj1);
console.log(obj1);//[1,2,3]
console.log(obj2);//['1','2','3']
obj2.push(4);
console.log(obj1);//[1,2,3]
console.log(obj2);//['1','2','3',4]
concat
functioncopyArray(arr){
varresult=[];
result=arr.concat();
returnresult;
}
varobj1=[1,2,3];
varobj2=copyArray(obj1);
console.log(obj1);//[1,2,3]
console.log(obj2);//[1,2,3]
obj2.push(4);
console.log(obj1);//[1,2,3]
console.log(obj2);//[1,2,3,4]
slice
functioncopyArray(arr){
varresult=[];
result=arr.slice();
returnresult;
}
varobj1=[1,2,3];
varobj2=copyArray(obj1);
console.log(obj1);//[1,2,3]
console.log(obj2);//[1,2,3]
obj2.push(4);
console.log(obj1);//[1,2,3]
console.log(obj2);//[1,2,3,4]
深拷贝
以上方法实现的仅是数组的浅拷贝,如果要实现数组的深拷贝,需要使用递归方法
functioncopyArray(arr,result){
varresult=result||[];
for(vari=0;i<arr.length;i++){
if(arr[i]instanceofArray){
result[i]=[];
copyArray(arr[i],result[i]);
}else{
result[i]=arr[i];
}
}
returnresult;
}
varobj1=[1,2,[3,4]];
varobj2=copyArray(obj1);
console.log(obj1[2]);//[3,4]
console.log(obj2[2]);//[3,4]
obj2[2].push(5);
console.log(obj1[2]);//[3,4]
console.log(obj2[2]);//[3,4,5]