深拷贝
2020-09-09 本文已影响0人
酒暖花深Q
<script>
const obj1 = {
age:20,
name:'lily',
address:{
city:'beijing'
},
arr:['a','b','c']
}
// const obj2 = obj1;
const obj2 = deepClone(obj1);
obj2.address.city = 'shanghai';
// console.log(obj1.address.city); //shanghai
console.log(obj1.address.city); //beijing
/*obj == obj1{} 要拷贝的对象*/
function deepClone(obj = {}){
// obj 不是对象或者为空直接返回
if(typeof obj !== 'object' || obj == null){
return
}
//初始化返回结果
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;
}
</script>