手写实现deepClone方法

//实现深拷贝
function deepCopy( target ){
  const newTarget = Array.isArray(target) ? [] : {};
  for (const key in target) {
    if (typeof target[key] === "object" && target[key] !== null) {
      newTarget[key] = deepCopy(target[key]);
    } else {
      newTarget[key] = target[key];
    }
  }
  return newTarget;
}
 
//测试
var test = [1,'a',{name:'lei',age:18}];
 
var copy2 = deepCopy(test);
copy2[2].name = 'zhang'
 
console.log(test);  ////[1,'a',{name:'lei',age:18}]  未受到影响

  

posted @ 2021-07-29 09:59  soon_k  阅读(109)  评论(0编辑  收藏  举报