浅拷贝:本质上是拷贝引用地址
let obj = {
str:"string",
fn:function(){
console.log("hello world")
},
arr:[1,2,3,[4,5]]
}
let shallowCopy = function(obj){
if(typeof obj != "object"||typeof obj == null){
return obj
}
let copyTarget = new obj.constructor()
for(let key in obj){
if(obj.hasOwnProperty(key)){
copyTarget[key] = obj[key]
}
}
return copyTarget
}
console.log(shallowCopy(obj))
console.log(shallowCopy(obj).fn)
简化的深拷贝:将整个对象拷贝到另一个地址栏
let obj = {
str:"string",
fn:function(){
console.log("hello world")
},
arr:[1,2,3,[4,5]]
}
let deepCopy = function(obj){
if(typeof obj != 'object'||typeof obj == null){
return obj
}
let copyTarget = new obj.constructor()
for(let key in obj){
if(obj.hasOwnProperty(key)){
copyTarget[key] = deepCopy(obj[key])
}
}
return copyTarget
}
console.log(shallowCopy(obj))
console.log(shallowCopy(obj).fn)
深拷贝-->处理循环引用情况-->也就是A引用B,B又引用A。这种情况下,如果是常规的递归会一直循环往复直到超出内存限制。-->map记录
let deepCopyPlus = function(obj,map = new Map()){
if(typeof obj != 'object'||typeof obj == null){
return obj
}
let copyTarget = new obj.constructor()
//添加一个map作为记录
if(map.has(obj)){
return map.get(obj)
}
map.set(obj,copyTarget)
for(let key in obj){
if(obj.hasOwnProperty(key)){
copyTarget[key] = deepCopyPlus(obj[key],map)
}
}
return copyTarget
}