- 相關(guān)推薦
JavaScript如何進(jìn)行數(shù)組復(fù)制
導(dǎo)語:JavaScript如何進(jìn)行數(shù)組復(fù)制?下面是小編給大家提供的數(shù)組復(fù)制代碼實(shí)現(xiàn),大家可以參考閱讀,更多詳情請(qǐng)關(guān)注應(yīng)屆畢業(yè)生考試網(wǎng)。
push
function copyArray(arr){
var result = [];
for(var i = 0; i < arr.length; i++){
result.push(arr[i]);
}
return result;
}
var obj1=[1,2,3];
var obj2=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
??使用該方法的缺點(diǎn)是數(shù)組中的項(xiàng)全部變成了字符串形式
function copyArray(arr){
var result = [];
result = arr.join().split(',');
return result;
}
var obj1=[1,2,3];
var obj2=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
function copyArray(arr){
var result = [];
result = arr.concat();
return result;
}
var obj1=[1,2,3];
var obj2=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
function copyArray(arr){
var result = [];
result = arr.slice();
return result;
}
var obj1=[1,2,3];
var obj2=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]
深拷貝
??以上方法實(shí)現(xiàn)的僅是數(shù)組的淺拷貝,如果要實(shí)現(xiàn)數(shù)組的深拷貝,需要使用遞歸方法
function copyArray(arr,result){
var result = result || [];
for(var i = 0; i < arr.length; i++){
if(arr[i] instanceof Array){
result[i] = [];
copyArray(arr[i],result[i]);
}else{
result[i] = arr[i];
}
}
return result;
}
var obj1=[1,2,[3,4]];
var obj2=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]