经常遇到深拷贝的问题在这里简单记录一下
深拷贝主要有三个需要注意的点
- 通过typeof判断拷贝的节点是否需要继续深度拷贝
- 通过hasOwnProperty判断是否为原型属性
- 通过instanceof判断节点是Array还是object
code
let x = {
a: 1,
b: '123',
c: '合肥',
d: ['1',2,3,4]
}
// 深拷贝函数
function deepClone(obj = {}){
if(typeof obj !== 'object' || typeof obj == null){
return obj
}
let res
if(res instanceof Array){
res = []
}else{
res = {}
}
for(let key in obj){
if(obj.hasOwnProperty(key)){
res[key] = deepClone(obj[key])
}
}
return res
}
let x1 = deepClone(x)
x1.a = 1000
console.log(x) // {a: 1, b: '123', c: '合肥', d: Array(4)}