JS 你最少用几行代码实现深拷贝?

前言:

深度克隆(深拷贝),一直都是面试的时候已经被问到的内容,网上介绍的实现方式也都各有千秋,大概有以下三种方式:

    1. JSON.parse() + JSON.stringify(),这个很好理解;

    2. 全量判断类型,根据类型做不同的处理;

    3. 第二种的处理,简化类型判断过程;

前两种比较常见,今天我们一起深度学习第三种。

1、问题分析

深拷贝 自然是相对 浅拷贝 而言的。我们都知道 引用数据类型 变量存储的是数据的引用,就是一个指向内存空间的指针,所以如果我们像赋值简单数据类型那样的方式赋值的话,其实只能赋值一个指针的引用,并没有实现真正的数据克隆

通过下面这个例子很容易就能理解:

    const obj = {
      name: 'Barry',
    }
    const obj2 = obj;
    obj.name = "Lau Barry";

    console.log('obj', obj); // obj {name: 'Lau Barry'}
    console.log('obj2', obj2); // obj2 {name: 'Lau Barry'}

所以 深度克隆 就是为了解决引用数据类型不能通过赋值的方式 复制 的问题;

2、引用数据类型

我们来罗列一下 引用数据数据类型有哪些:

·ES6之前:Object、Array、Date、RegExp、Error

·ES6之后:Map、Set、WeakMap、WeakSet

 所以,我们要深度克隆,就要对数据进行遍历并根据类型采取相应的克隆方式。当然因为数据会存在多层嵌套的情况,采用 递归 是不错的选择

3、简单粗暴的深拷贝版本

    function deepClone (obj) {
      let res = {};

      // 类型判断的通用方法
      function getType (val) {
        // return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
        return Object.prototype.toString.call(val).slice(8, -1);
      }

      const type = getType(obj);
      console.log('type', type);
      const reference = ['Set', 'WeakSet', 'Map', 'WeakMap', 'Date', 'RegExp', 'Error']
      switch (type) {
        case 'Object':
          for (const key in obj) {
            // Object的hasOwnProperty()方法返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。
            if (Object.hasOwnProperty.call(obj, key)) {
              res[key] = deepClone(obj[key])
            }
          }
          break;
        case 'Array':
          obj.forEach((t, i) => {
            res[i] = deepClone(t)
          })
          break;
        case 'Date':
          res = new Date(obj);
          break;
        case 'RegExp':
          res = new RegExp(obj);
          break;
        case 'Map':
          res = new Map(obj);
          break;
        case 'Set':
          res = new Set(obj);
          break;
        case 'WeakMap':
          res = new WeakMap(obj);
          break;
        case 'WeakSet':
          res = new WeakSet(obj)
          break;
        case 'Error':
          res = new Error(obj)
          break;
        default:
          res = obj;
          break;
      }
      return res
    }

    const res = {
      name: 'barry',
      age: 18,
      hobby: ['健身', '游泳', '读书'],
      about: {
        height: 180,
        weight: 155,
      }
    }
    const res2 = deepClone(res);
    res2.name = 'barry222';
    res2.hobby[3] = '看报';
    res2.about['eat'] = 'meat'

    console.log('res', res);
    console.log('res2', res2);

其实这就是我们最前面提到的第二种方式,很傻对不对,一眼就能看出来有很多冗余代码可以合并。

4、基本优化 --- 合并冗余代码

将一眼就能看出来的冗余代码合并一下

    function deepClone (obj) {
      let res = null;

      // 类型判断的通用方法
      function getType (val) {
        // return Object.prototype.toString.call(val).slice(8, -1).toLowerCase();
        return Object.prototype.toString.call(val).slice(8, -1);
      }

      const type = getType(obj);
      console.log('type', type);
      const reference = ['Set', 'WeakSet', 'Map', 'WeakMap', 'Date', 'RegExp', 'Error']

      if (type === 'Object') {
        res = {};
        for (const key in obj) {
          if (Object.hasOwnProperty.call(obj, key)) {
            res[key] = deepClone(obj[key])
          }
        }
      } else if (type === 'Array') {
        res = [];
        obj.forEach((t, i) => {
          res[i] = deepClone(obj[t])
        })
      } else if (reference.includes(type)) {
        res = new obj.constructor(obj)
      } else {
        res = obj
      }
      return res
    }

为了验证代码的正确性,我们用下面这个数据验证下:

    const res = {
      cardID: Symbol(411381),
      name: 'barry',
      age: 18,
      smoke: false,
      money: null,
      hobby: ['健身', '游泳', '读书'],
      about: {
        height: 180,
        weight: 155,
      },
      say: () => {
        console.log('say Hello');
      },
      calc: function (a, b) {
        return a + b
      },
    }
    const res2 = deepClone(res);
    res2.name = 'barry222';
    res2.hobby[3] = '看报';
    res2.about['eat'] = 'meat'

    console.log('res', res);
    console.log('res2', res2);

执行结果:

5、还有进一步优化的空间吗?

答案当然是肯定的

    // 把判断类型的方法移到外部,避免递归的过程中多次执行
    // 类型判断的通用方法
    function getType (val) {
      return Object.prototype.toString.call(val).slice(8, -1);
    }

    function deepClone (obj) {
      let res = null;
      const reference = ['Set', 'WeakSet', 'Map', 'WeakMap', 'Date', 'RegExp', 'Error']

      if (reference.includes(obj?.constructor)) {
        res = new obj.constructor(obj)
      } else if (Array.isArray(obj)) {
        res = [];
        obj.forEach((t, i) => {
          res[i] = deepClone(t)
        })
      } else if (typeof obj === 'object' && obj !== null) {
        res = {};
        for (const key in obj) {
          if (Object.hasOwnProperty.call(obj, key)) {
            res[key] = deepClone(obj[key])
          }
        }
      } else {
        res = obj
      }
      return res
    }

    const res = {
      cardID: Symbol(411381),
      name: 'barry',
      age: 18,
      smoke: false,
      money: null,
      hobby: ['健身', '游泳', '读书'],
      about: {
        height: 180,
        weight: 155,
      },
      say: () => {
        console.log('say Hello');
      },
      calc: function (a, b) {
        return a + b
      },
    }
    const res2 = deepClone(res);
    res2.name = 'barry222';
    res2.hobby[3] = '看报';
    res2.about['eat'] = 'meat'
    res2.about.height = 185;
    res2.money = 999999999999;
    console.log('res', res);
    console.log('res2', res2);

6、最后,还有循环引用问题,避免出现无限循环的问题

我们用hash来存储已经加载过的对象,如果已经存在的对象,就直接返回。

    function deepClone (obj, hash = new WeakMap()) {
      if (hash.has(obj)) {
        return obj
      }
      let res = null;
      const reference = ['Set', 'WeakSet', 'Map', 'WeakMap', 'Date', 'RegExp', 'Error'];

      if (reference.includes(obj?.constructor)) {
        res = new obj.constructor(obj)
      } else if (Array.isArray(obj)) {
        res = [];
        obj.forEach((t, i) => {
          res[i] = deepClone(t)
        })
      } else if (typeof obj === 'object' && obj !== null) {
        hash.set(obj);
        res = {};
        for (const key in obj) {
          if (Object.hasOwnProperty.call(obj, key)) {
            res[key] = deepClone(obj[key], hash)
          }
        }
      } else {
        res = obj
      }
      return res
    }

    const res = {
      cardID: Symbol(411381),
      name: 'barry',
      age: 18,
      smoke: false,
      money: null,
      hobby: ['健身', '游泳', '读书'],
      about: {
        height: 180,
        weight: 155,
      },
      say: () => {
        console.log('say Hello');
      },
      calc: function (a, b) {
        return a + b
      },
    }
    const res2 = deepClone(res);
    res2.name = 'barry222';
    res2.hobby[3] = '看报';
    res2.about['eat'] = 'meat'
    res2.about.height = 185;
    res2.money = 999999999999;
    console.log('res', res);
    console.log('res2', res2);

猜你喜欢

转载自blog.csdn.net/weixin_56650035/article/details/123973205