深拷贝递归

function deepClone(source){
// [] => Array(基类) {}=> Object
const targetObj = source.constructor === Array ? []:{};
for(let keys in source){
if(source.hasOwnProperty(keys)){
// keys => 3种(基本,数组,对象)
//引用数据类型
if(source[keys] && typeof source[keys] === 'object'){
targetObj[keys] = source[keys].constructor === Array ? [] : {};
//递归
targetObj[keys] =deepClone(source[keys])
}else{
//基本数据类型,直接赋值
targetObj[keys] = source[keys];
}
}
}
return targetObj
}

let objC = {
ff:'name',
hh:1,
obj:{str:'111',age:12},
arr:[1,2,3,4]
}
let newObjC = deepClone(objC);
newObjC.ff = "xxxx"
newObjC.arr.push('1111')

posted @ 2022-04-07 18:03  ajaXJson  阅读(22)  评论(0编辑  收藏  举报