數組複製

前面的話

  前面的博文中介紹了對象拷貝,本文將詳細介紹數組複製html

 

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

  使用該方法的缺點是數組中的項所有變成了字符串形式數組

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]

 

深拷貝

  以上方法實現的僅是數組的淺拷貝,若是要實現數組的深拷貝,須要使用遞歸方法code

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]
相關文章
相關標籤/搜索