⚡️JS 实现深拷贝(快来探讨吧~)

38 阅读3分钟

“我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情

一、实现深拷贝思路

  • 对数据类型进行区分

    • Number String Boolean null undifined Symbol bigInt(可直接返回该类型数据)
    • Object(通过函数进行判断具体返回什么类型)
  • 步骤

    • instanceof Object === true类型进行判断

      • 对为Function类型进行判断

        • 返回普通函数
        • 返回箭头函数
      • 对为Array类型进行判断

      • 对为Date类型进行判断

      • 对为RegExp类型进行判断

      • 其他

      • 返回数组

      • 对实例的属性进行遍历

      • 为将要返回的值result身上添加当前实例的属性(需要对该属性做递归操作)

      • 返回result

    • 其他类型

      • 返回实例

二、实现代码(版本一)

const deepClone = (a) => {
  if (a instanceof Object) {
    let result; // 对返回值进行存储
    if (a instanceof Function) {
      // 通过prototype属性区分是箭头函数还是普通函数(暂时忽略generator函数和await函数)
      if (a.prototype) {
        result = function () { return a.apply(this, arguments); }
      } else {
        result = (...args) => a.apply(undefined, ...args); // 箭头函数没有this
      }
    } else if (a instanceof Array) {
      result = [];
    } else if (a instanceof Date) {
      result = new Date(a - 0); // 用时间戳减0可生成数字,再转换成Date
    } else if (a instanceof RegExp) {
      // result = new RegExp(a);
      result = new RegExp(a.source, a.flags);
    } else {
      result = {};
    }

    // 将a身上的属性添加到result中(function也存在别的属性的可能的)
    for (let key in a) {
      result[key] = a[key]; // error:未解决值为引用对象的问题
    }

    return result;
  } else {
    return a;
  }
}

注意点:

  1. 箭头函数:返回的函数的this是指向undifined的,因为箭头函数就不存在 this
  2. Date:new Date() - 0返回的是一串数字,其值是可以作为 new Date() 的参数

三、实现代码(版本二)

问题:对值为引用类型无法完全深拷贝

当我们为 result 遍历添加属性到其身上时,如果要添加的属性a[key]是个引用对象,那么就得再对这个对象进行深拷贝,不然的话当修改result[key]的值,会修改a[key],那就不是深拷贝了

解决方法:

for (let key in a) {
  result[key] = deepClone(a[key]); // error:未解决值为引用对象的问题
}

四、实现代码(版本三)

问题:当 a 继承了父的属性,for...in会将继承属性同样深拷贝

解决方法:

for (let key in a) {
  // 通过是否为a身上属性来判断
  if (a.hasOwnProperty(key)) {
    result[key] = deepClone(a[key]);
  }
}

五、实现代码(最终版本)

问题:

a.self = a;
let b = deepClone(a)

就会如下图出现「环」

因为它会沿着自己的 self 不停的套娃,会出现溢栈

解决方法:

通过标记的方法,给走过的地方做一个标记,当访问这个节点的时候,如果是访问过的,就直接返回这个结点就可;否则的话做个标记

但是这个标记通过什么方式标记好呢?因为键的类型有多种,所以通过「Map」方式最合适

最终代码:

const deepClone = (a, cache) => {
  if (!cache) {
    cache = new Map();
  }
  if (cache.get(a)) {
    return cache.get(a);
  }
  if (a instanceof Object) {
    let result; // 对返回值进行存储
    if (a instanceof Function) {
      // 通过prototype属性区分是箭头函数还是普通函数(暂时忽略generator函数和await函数)
      if (a.prototype) {
        result = function () { return a.apply(this, arguments); }
      } else {
        result = (...args) => a.apply(undefined, ...args); // 箭头函数没有this
      }
    } else if (a instanceof Array) {
      result = [];
    } else if (a instanceof Date) {
      result = new Date(a - 0); // 用时间戳减0可生成数字,再转换成Date
    } else if (a instanceof RegExp) {
      // result = new RegExp(a);
      result = new RegExp(a.source, a.flags);
    } else {
      result = {};
    }
    // 将当前节点标识已访问过
    cache.set(a, result);
    // 将a身上的属性添加到result中(function也存在别的属性的可能的)
    for (let key in a) {
      // 通过是否为a身上属性来判断
      if (a.hasOwnProperty(key)) {
        result[key] = deepClone(a[key], cache);
      }
    }
    return result;
  } else {
    return a;
  }
}

const a = {
  number: 1, bool: false, str: 'hi', empty1: undefined, empty2: null,
  array: [
    { name: 'frank', age: 18 },
    { name: 'jacky', age: 19 }
  ],
  date: new Date(2000, 0, 1, 20, 30, 0),
  regex: /.(j|t)sx/i,
  obj: { name: 'frank', age: 18 },
  f1: (a, b) => a + b,
  f2: function (a, b) { return a + b }
}

a.self = a;
let b = deepClone(a);
console.log(b === b.self); // true