XingGuoZM/FE-blog

笔试题五:手写深克隆

Opened this issue · 0 comments

深克隆

const myDeepClone=(target)=>{
  if(typeof target === 'object'){
    const obj = Array.isArray(target)?[]:{};
    for(let item in target){
      obj[item] = target[item];
    }
    return obj;
  }else{
    return target;
  }
}

测试

  const obj ={a:1,b:2};
  const cloneObj = myDeepClone(obj);
  cloneObj.a=2;
  console.log(obj,cloneObj)