//缓存已经处理的obj,不然环形报错
let cacheMap=new WeakMap()
function deepClone(obj){
//基本类型,数值 null之类的
if(typeof obj!=='object'||!obj){
return obj;
}
if(cacheMap.has(obj)){
//存在就直接返回
return cacheMap.get(obj)
}
//正则
if(obj instanceof RegExp){
let tmp=new RegExp(obj)
cacheMap.set(obj,tmp)
return tmp;
//map
}else if(obj instanceof Map){
let tmp=new Map()
cacheMap.set(obj,tmp)
obj.forEach((val,key)=>{
tmp.set(deepClone(key),deepClone(val))
})
return tmp;
//set
}else if(obj instanceof Set){
let tmp=new Set()
cacheMap.set(obj,tmp)
obj.forEach((val)=>{
tmp.add(deepClone(val))
})
return tmp;
//obj等
}else{
let tmp=new obj.constructor()
cacheMap.set(obj,tmp)
for(let key in obj){
tmp[key]=deepClone(obj[key])
}
return tmp
}
}
对象的深拷贝
于 2022-11-08 19:08:00 首次发布