a = [1, 2]
b = [3, 4, a]
a.push(b)
function deepClone(data, arr = []) {
// 1. deepClone 基本类型判断返回
if (data instanceof Date) {
return new Date(data)
}
if (data instanceof RegExp) {
return new RegExp(data)
}
if (data === null || typeof data !== "object") {
return data
}
// 2. 查找是否存在循环引用的情况
let obj = arr.find(item => {
return item.val === data
})
// 3. 如果存在 需要将已经深拷贝的该值直接返回
if (obj) {
return obj.copy
}
// 4. 创建 copy的对象
let copy = Array.isArray(data) ? [] : {}
arr.push({
val: data,
copy
})
// 5. 深度遍历拷贝
Object.keys(data).forEach(key => {
copy[key] = deepClone(data[key], arr)
})
return copy
}
console.log(deepClone(a)); // <ref *1> [ 1, 2, [ 3, 4, [Circular *1] ] ]
深拷贝如何解决循环引用的情况
最新推荐文章于 2024-01-25 15:55:51 发布