平时使用数组复制时,我们大多数会使用‘=’,这只是浅拷贝,存在很多问题。比如
let arr = [1,2,3,4,5];
let arr2 = arr;
console.log(arr) //[1, 2, 3, 4, 5]
console.log(arr2) //[1, 2, 3, 4, 5]
arr[0] = 6;
console.log(arr) //[6, 2, 3, 4, 5]
console.log(arr2) //[6, 2, 3, 4, 5]
arr2[4] = 7;
console.log(arr) //[6, 2, 3, 4, 7]
console.log(arr2) //[6, 2, 3, 4, 7]
很明显,浅拷贝下,拷贝和被拷贝的数组会相互受到影响。所以,必须要有一种不受影响的方法,那就是深拷贝。
深拷贝的实现方式有很多种。
一:for循环实现深拷贝
//for循环copy
function copy(arr) {
let cArr = []
for(let i = 0; i < arr.length; i++){
cArr.push(arr[i])
}
return cArr;
}
let arr3 = [1,2,3,4];
let arr4 = copy(arr3) //[1,2,3,4]
console.log(arr4) //[1,2,3,4]
arr3[0] = 5;
console.log(arr3) //[5,2,3,4]
console.log(arr4) //[1,2,3,4]
二:slice方法实现深拷贝
//slice实现深拷贝
let arr5 = [1,2,3,4];
let arr6 = arr5.slice(0);
arr5[0] = 5;
console.log(arr5); //[5,2,3,4]
console.log(arr6); //[1,2,3,4]
三:concat实现深拷贝
//concat实现深拷贝
let arr7 = [1,2,3,4];
let arr8 = arr7.concat();
arr7[0] = 5;
console.log(arr7); //[5,2,3,4]
console.log(arr8); //[1,2,3,4]
四:es6扩展运算实现深拷贝
//es6扩展运算实现深拷贝
let arr9 = [1,2,3,4];
let [...arr10] = arr9;
arr9[0] = 5;
console.log(arr9) //[5,2,3,4]
console.log(arr10) //[1,2,3,4]
五:对象的循环深拷贝
// 循环copy对象
let obj = {
id:'0',
name:'king',
sex:'man'
}
let obj2 = copy2(obj)
function copy2(obj) {
let cObj = {};
for(var key in obj){
cObj[key] = obj[key]
}
return cObj
}
console.log(obj) //{id: "0", name: "king", sex: "man"}
console.log(obj2) //{id: "0", name: "king", sex: "man"}
六:对象转换成json实现深拷贝
//转换成json
let obj3 = JSON.parse(JSON.stringify(obj));
console.log(obj3) //{id: "0", name: "king", sex: "man"}
七:es6扩展运算实现深拷贝
let {...obj4}= obj
console.log(obj4) //{id: "0", name: "king", sex: "man"}
总结:深刻理解javascript的深浅拷贝,可以灵活的运用数组,并且可以避免很多bug。