const obj1{
age: 20,
name: 'xxx',
address: {
city: 'beijing'
}
arr: ['a', 'b', 'c']
}
const obj2 = obj1
obj2.address.city = 'shanghai'
console.log(obj1.address.city) //shanghai 浅拷贝
const obj3 = deepClone(obj1)
obj3.address.city = 'tianjin'
console.log(obj1.address.city) //还是shanghai 深拷贝
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
}
标签:obj1,city,面试题,obj,前端,result,key,address,拷贝 From: https://www.cnblogs.com/ALAN-BABABA/p/17131082.html