前端面试题-手写一个深拷贝

    function deepClone(source) {
        const targetObj = source.constructor === Array ? [] : {};
        for (let keys in source) {
          // 引用数据类型
          if (source[keys] && typeof source[keys] === "object") {
            // 维护层代码
            targetObj[keys] = source.constructor === Array ? [] : {};
            // 递归调用
            targetObj[keys] = deepClone(source[keys]);
          } else {
            // 基本数据类型
            targetObj[keys] = source[keys];
          }
        }
        return targetObj;
      }

      let obj = {
        ff: "name",
        array: [1, 2, 3, 4],
        ooo: {
          id: 2,
          name: "张三",
        },
      };
      let newObj = deepClone(obj);
      newObj.array.push("哈哈哈哈");
      console.log(newObj);

猜你喜欢

转载自blog.csdn.net/znhyXYG/article/details/126580182