JS的深拷贝方法

简单的深复制,只会复制对象的属性值,不会复制对象的原型对象和方法,复制Map和Set时会将其转换成Array

function clone(obj){
  return JSON.parse(JSON.stringify(obj));
}

普通的深复制,可以完全复制一个对象,包括对象的原型对象和方法,不包括Map和Set

function clone(obj){
  if(typeof obj !== 'object'){
    return obj;
  }
  let cloneObj = obj.constructor===Array?[]:{};
  for(var property in obj){
    cloneObj[property] = typeof obj[property]==='object'?clone(obj[property]):obj[property];
  }
  return cloneObj;
}

完美的深复制,可以完全复制一个对象,包括对象的原型对象和方法,包括Map和Set

function clone(obj){
  if(typeof obj!=='object'){return obj;}
  let cloneObj = {};
  switch(obj.constructor){
    case Array:
      cloneObj = [];
    case Object:
      for(var property in obj){
        cloneObj[property] = typeof obj[property] === 'object'?clone(obj[property]):obj[property];
      }
      break;
    case Map:
      cloneObj = new Map();
      obj.forEach((value,key)=>{
        cloneObj.set(key,typeof value==='object'?clone(value):value);
      });
      break;
    case Set:
      cloneObj = new Set();
      obj.forEach(value=>{
        cloneObj.add(typeof value==='object'?clone(value):value);
      });
      break;
  }
  return cloneObj;
}

你可能感兴趣的:(JavaScript,前端)