有关深拷贝
2020-12-02 本文已影响0人
木羽木羽女口生
/**
*深拷贝
*/
const obj1 = {
age:20,
name:'xxx',
adress:{
city:'beijing'
},
arr:['a','b','c']
}
const obj2= deepClone(obj1)
obj2.address.city = 'shanghai'
console.log(obj1.address.city)
/**
*
*深拷贝
* @param {Object} obj 要拷贝的对象
*/
function deepClone(obj = {}){
if(typeof obj !== 'object' || obj == null){
//如果obj 是null,或不是对象和数组,直接返回
return {}
}
//初始化返回结果
let result
if(result instanceof Array){
result = []
}else{
result = {}
}
for (const key in obj) {
//保证key 不是原型的属性
if (obj.hasOwnProperty(key)) {
//递归的调用!!
result[key] = deepClone(obj[key]);
}
}
return result
}