实现深拷贝有很多方法
一、数组的深拷贝
1、for 循环实现数组的深拷贝
代码语言:javascript复制var arr1 = [1,2,3,4,5,6]
var arr2 = copyArray(arr1)
function copyArray(arr) {
let res = [];
for (let i = 0; i < arr.length; i ) {
res.push(arr[i])
}
return res;
}
2、slice方法实现数组的深拷贝
代码语言:javascript复制var arr = [1,2,3,4,5];
var arr2 = arr.slice(0);
arr[2] = 5;
console.log(arr);
console.log(arr2);
3、concat 方法实现数组的深拷贝
代码语言:javascript复制var arr = [1,2,3,4,5];
var arr2 = arr.concat();
arr[2] = 5;
console.log(arr);
console.log(arr2);
4、ES6扩展运算符实现数组的深拷贝
代码语言:javascript复制var arr = [1,2,3,4,5];
var [ ...arr2 ] = arr;
arr[2] = 5;
console.log(arr);
console.log(arr2);
二、对象的深拷贝
1、for循环实现对象的深拷贝
代码语言:javascript复制var obj = {
name: 'FungLeo',
sex: 'man',
old: '18'
}
var obj2 = copyObj(obj)
function copyObj(obj) {
let res = {}
for (var key in obj) {
res[key] = obj[key]
}
return res
}
2、json字符串方式实现对象的深拷贝
代码语言:javascript复制var obj = {
name: 'test',
sex: 'man',
old: '18'
}
var obj2 = JSON.parse(JSON.stringify(obj));
3、ES6扩展运算符实现对象的深拷
代码语言:javascript复制var obj = {
name: 'FungLeo',
sex: 'man',
old: '18'
};
var { ...obj2 } = obj;
obj.old = '22';
console.log(obj);
console.log(obj2);
本文部分参考:https://blog.csdn.net/github_38885296/article/details/81057028