//声明待拷贝对象 obj2
let obj2={
age:18,
name: "lirong",
pattners: {
zhangsan: {
age: 19,
name: "zhangsan"
},
lisi:{
age: 20,
name: "lisi",
pattners :[ {name:'甲',age: 18}, {name:'乙'},{name:'丙'},{name:'丁'},'']
}
}
};
/**
* 递归深拷贝对象
* @param {*} obj 参数是对象或者数组
*/
function copyObj(obj={}){
if(obj==null || typeof obj!== 'object')//判断是不是对象或者数组
{
return obj ;
}
let newobj;
if(obj.constructor === Array){//如果是数组 初始化数组形式
newobj=[];
}
else{//是对象
newobj={};
}
for(let key in obj){ //遍历并拷贝 如果当前节点是对象继续往下遍历
newobj[key]= copyObj(obj[key]);
}
return newobj;
}
let copyobjresult=copyObj(obj2);
copyobjresult.age=22;
console.log( obj2);//结果 obj2.age 是18
console.log( copyobjresult);//结果 copyobjresult.age 是22 两个对象互不影响,深拷贝实现