深拷贝实现笔记

拷贝只相对于引用类型来探讨

只是相对一维数组拷贝
Array.slice()
Array.concat()
Array.from()
Object.assign()

不能拷贝undefined和函数和symbol
JSON.parse(JSON.stringify(obj))
undefined和任意函数和symbol

深拷贝实现
function deepCopy(obj, parent = null) {
// 创建一个新对象
let result = {}
let keys = Object.keys(obj)
key = null
temp = null
_parent = parent
// 字段有父级需要追溯字段的父级
while (_parent) {
// 字段引用了父级则为循环引用
if (_parent.originalParent === obj) {
return _parent.currentParent
}
_parent = _parent.parent
}
for (let i = 0; i < keys.length; i++) {
key = keys[i]
temp = obj[key]
// 字段的值也是一个对象
if (temp && typeof temp === 'object') {
// 将同级待拷贝对象和新对象传递给parent方便追溯循环引用
result[key] = deepCopy(temp, {
originalParent: obj,
currentParent: result,
parent: parent
})
} else {
result[key] = temp
}
}
return result
}

var obj1 = {
x: 1,
y: function(){
console.log('222')
},
z: undefined
}
obj1.k = obj1
var obj2 = deepCopy(obj1)
console.log(obj1)
console.log(obj2)

原文地址:https://www.cnblogs.com/victory820/p/9014745.html