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)

你可能感兴趣的:(js深度克隆)