手写深拷贝

48 阅读1分钟

使用JSON

const x = JSON.parse(JSON.stringify(a))

缺点:

  1. 不支持Date、正则、undefined、函数等数据
  2. 不支持引用(环装结构)

递归

要点:

  1. 递归

  2. 判断类型

  3. 检查环

  4. 不拷贝原型上的属性

const deepClone = (a, cache) => {
  if (!cache) {// 设置缓存避免环形引用报错
    cache=new Map()//用map因为map的key可以是对象
  }
  if (a instanceof Object) {
    if (cache.get(a)) { return cache.get(a) }
    let result;
    if (a instanceof Function) {
      if (a.prototype)  {
        result=function(){return a.apply(this,arguments)
        }
      } else {//箭头函数
        result=(...args)=>{return a.call(undefined,...args)}
      }
    }
    else if (a instanceof Array) {
      result=[]
    }
    else if (a instanceof Date) {
      result=new Date(a-0)
    }
    else if (a instanceof RegExp) {
      result=new RegExp(a)
    }
    else {
      result={}
    }
    cache.set(a, result)
    for (let key in a) {
      if (a.hasOwnProperty(key)) {//不拷贝从原型继承来的属性
        result[key]=deepClone(a[key],cache)
      }
    }
    return result
  } else {
    return a
  }
}