js深拷贝— 递归拷贝

196 阅读1分钟
function deepClone(target) {
      let result;
      if (typeof target === 'object') {
          if (Array.isArray(target)) { // 判断是数组 也可用 target.constructor === Array
            result = []; // 将result赋值为一个数组,并且执行遍历
            for (let i in target) {
              result.push(deepClone(target[i])) // 递归克隆数组中的每一项
            }
          } else if (target === null) {
              result = null; // 判断如果当前的值是null的话;直接赋值为null
          } else if (target.constructor === RegExp){
              result = target; // 判断如果当前的值是一个RegExp对象的话,直接赋值    
          } else {
              result = {}; // 否则是普通对象,直接for in循环,递归赋值对象的所有值
              for (let i in target) {
                  result[i] = deepClone(target[i]);
              }
          }
      } else {
          result = target; // 如果不是对象的话,就是基本数据类型,那么直接赋值
      }
      return result;
  }

实例:

  let obj1 = {
      a: {
          c: /a/,
          d: undefined,
          b: null
      },
      b: function () {
          console.log(this.a)
      },
      c: [
          {
              a: 'c',
              b: /b/,
              c: undefined
          },
          'a',
          3
      ]
  }
  let obj2 = deepClone(obj1);
  console.log(obj2);

感谢文章: www.jianshu.com/p/f4329eb1b…

如果本文对你有所帮助,感谢点一颗小心心,您的支持是我继续创作的动力!