const =obj1={
name:‘xxx’,
age:‘18’,
adress:{
city:‘杭州’
},
love:[‘旅游’,‘跳舞’]
}
function deepClone(obj={}){
if(typeof obj !== 'object' || obj==null){
//判断obj是null,或者不是对象和数组,直接返回
return obj
}
let result
if(obj instanceof Array){
result=[]
}else{
result={}
}
for(let key in obj){
// 保证key 不是原型的属性
if(obj.hasOwnProperty(key)){
//递归调用
result[key]=deepClone(obj[key])
}
}
return result
}
使用:
const obj1= deepClone(obj)