数组对象的深拷贝
2019-11-14 本文已影响0人
nzjcnjzx
let arr = [1, {a: 2}];
function deepCopy(arr) {
let copyArr = (arr.constructor === Array) ? [] : {}; // 判断是数组还是对象
for(let i in arr) {
if(typeof arr[i] === 'object') { // 判断是值类型还是引用类型
copyArr[i] = deepCopy(arr[i]); // 引用类型的话进行递归操作
} else {
copyArr[i] = arr[i]; // 值类型直接赋值
}
}
return copyArr;
}
let copyArr = deepCopy(arr);
console.log(copyArr ) // [1, {a: 2}]
arr[1].a = 3;
console.log(copyArr ) // [1, {a: 2}]
copyArr[1].a = 5;
console.log(arr) // [1, {a: 2}
对象深拷贝
var obj = { a: 1, b: { c: 2 }};
// 深拷贝
var newObj = JSON.parse(JSON.stringify(obj));
function copyArr(arr) {
const newArr = []
arr.forEach(item => {
const {...obj} = item
newArr.push(obj)
})
return newArr
}
function DeepCopy(object) {
let resultObject = {};
for (let obj in object) {
if (typeof (object[obj]) == "object" && !Array.isArray(object[obj])) {
let x = {}
x[obj] = DeepCopy(object[obj])
Object.assign(resultObject, x);
} else {
let x = {};
x[obj] = object[obj];
Object.assign(resultObject, x);
}
}
return resultObject;
}