一个完美的深拷贝

一个完美的深拷贝_第1张图片
    function deepClone(target, map = new WeakMap()) {
      if (target === null) return target;
      if (target instanceof Date) return new Date(target);
      if (target instanceof Set) return new Set([...target]);
      if (target instanceof Map) return new Map([...target]);
      if (target instanceof RegExp) return new RegExp(target);
      if (target instanceof HTMLElement) return target;

      if (typeof target !== "object") return target;

      if (map.get(target)) return map.get(target);
      const cloneTarget = new target.constructor();
      map.set(target, cloneTarget);

      Reflect.ownKeys(target).forEach((key) => {
        cloneTarget[key] = deepClone(target[key], map);
      });
      return cloneTarget;
    }

测试代码:

    // 特殊类型
    // let target = null;
    // let target = new Date();
    // let target = new Set([10, 10, 12, 14, { name: "zzz" }]);
    // let target = new Map([
    //   [
    //     ["watermelon", "fruit"],
    //     ["cat", "animal"],
    //   ],
    // ]);
    // let target =
    //   /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(0[1-9]|1[1-9]|2[1-9])$/;
    // let target = ``;

    // 原始类型
    // let target = 3;

    let target = {
      name: "张三",
      info: {
        age: 18,
      },
      fun: function () {
        console.log("111");
      },
    };
    target.target = target;
    console.log(deepClone(target));

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