深拷贝
- 判断要拷贝的对象类型(是简单类型还是复杂类型)
function isComplexData (data) {
if(data===null||data===undefined){
return false
}
let flag = data.constructor===Array||data.constructor===Object
return flag
}
- 递归拷贝函数
function deepCopy (data) {
if(!isComplexData (data)){
return data
}
let result = null
if(data.constructor===Array){
result = []
}else{
result = {}
}
for(let i in data){
result[i] = deepCopy (data[i])
}
return result
}
- 验证
let a = {n:{x:0,y:1},m:2}
let b = deepCopy (a)
console.log(a,b)
a.n.x = 3
console.log(a,b)
打印结果:
{ n: { x: 0, y: 1 }, m: 2 } { n: { x: 0, y: 1 }, m: 2 }
{ n: { x: 3, y: 1 }, m: 2 } { n: { x: 0, y: 1 }, m: 2 }