说明: 浅拷贝对于深层对象引用无法处理
1. 一般使用Object.assign 即可实现单层对象的深拷贝, 但对于多层对象无法生效
2. 一般通过JSON.parse() 和JSON.stringfy() 即可实现简单的深拷贝, 但对于正则, 日期对象等无法完整拷贝如下图所示
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/db592ab6ae206fbdcd6dddae8a20fdd9.png#pic_center)
实现深拷贝
1. 简单的深拷贝
function deepClone (obj) {
let newObj
if (typeof obj === 'object') {
newObj = {}
for(let i in obj) {
newObj[i] = deepClone(obj[i])
}
} else if (typeof obj === 'array') {
newObj = []
for(let i = 0; i < obj.length; i++) {
newObj[i] = deepClone(obj[i])
}
} else {
newObj = obj
}
return obj
}
2. 解决上述问题的深拷贝
function checkType (any) {
return Object.prototype.toString.call(any).slice(8, -1)
}
function deepClone (obj) {
let type = checkType(obj)
let newObj
if (type === 'Object') {
newObj = {}
for(let i in obj) {
newObj[i] = deepClone(obj[i])
}
} else if (type === 'Array') {
newObj = []
for(let i = 0; i < obj.length; i++) {
newObj[i] = deepClone(obj[i])
}
} else if (type === 'Function') {
newObj = new Function(`return ${obj.toString()}`).call(this)
} else if (type === 'Date') {
newObj = new Date(obj.getTime())
} else if (type === 'RegExp') {
newObj = new RegExp(obj)
} else if (type === 'Map') {
newObj = new Map()
obj.forEach((val, key) => {
newObj.set(key, deepClone(val))
})
} else if (type === 'Set') {
newObj = new Set()
for(let val of obj.values()) {
newObj.add(deepClone(val))
}
} else {
newObj = obj
}
return newObj
}