js深度克隆

function getType(data){
  return Object.prototype.toString.call(data).slice(8,-1)
}
function deepClone(data){
  let type = getType(data) , obj;
  if(type === 'Array'){
    obj = []
    data.forEach(item=>obj.push( deepClone(item) ))
  }else if(type === 'Object'){
    obj = {}
    for(let key in data){
      obj[key] = deepClone(data[key])
    }
  }else{
    return data
  }
  return obj
}

let obj1 = {a:1,b:{c:2,d:[3,4,{e:5}] }} ,
    obj2 = deepClone(obj1);
    obj2.b.d[2].e = 6
console.log(obj1 , obj2)
    原文作者:小白_pk
    原文地址: https://www.jianshu.com/p/6560f0980c36
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞