实现一个深拷贝

 如果你是应对面试,那你可以完全可以把这段代码背下来,hhh

function deepClone(obj, hash = new WeakMap()) {
  if (obj === null) {
    return null;
  }

  if (obj instanceof Date) {
    return new Date(obj);
  }

  if (obj instanceof RegExp) {
    return new RegExp(obj);
  }

  if (typeof obj !== "object") {
    return obj;
  }

  //处理对象的循环引用
  if (hash.has(obj)) {
    return hash.get(obj);
  }
  const resObj = Array.isArray(obj) ? [] : {};
  hash.set(obj, resObj);

  Reflect.ownKeys(obj).forEach((key) => {
    resObj[key] = this.deepClone(obj[key], hash);
  });
  return resObj;
}

猜你喜欢

转载自blog.csdn.net/m0_56274171/article/details/124188491