JSON.parse(JSON.stringify())
循环引用会报错, 不能拷贝函数
function deepClone1(target) {
const result = JSON.parse(JSON.stringify(target))
return result
}
const obj = {
a: 1,
b: ['e', 'f', 'g'],
c: {h: 20},
d: function() {}
}
obj.b.push(obj.c)
obj.c.j = obj.b
const result = deepClone1(obj)
console.log(obj)
console.log(result)
究极解决方案:
function deepClone2(target, map = new Map()) {
if(typeof target === 'object' && target !== null) {
let cache = map.get(target)
if(cache) {
return cache
}
let isArray = Array.isArray(target)
const result = Array.isArray(target) ? [] : {}
map.set(target, result)
if(isArray) {
target.forEach((item, index) => {
result[index] = deepClone2(item, map)
})
} else {
Object.keys(target).forEach(key => {
result[key] = deepClone2(target[key], map)
})
}
return result
} else {
return target
}
}
const obj = {
a: 1,
b: ['e', 'f', 'g'],
c: {h: 20},
d: function() {}
}
obj.b.push(obj.c)
obj.c.j = obj.b
const result = deepClone2(obj)
console.log(obj)
console.log(result)
|