双语面试:实现一个深拷贝函数

6 阅读1分钟

面试题 Interview Question

实现一个函数 deepClone,对任意复杂对象进行深拷贝,返回一个完全独立的副本。
Implement a function deepClone that performs a deep copy of any complex object and returns a completely independent duplicate.

要求 Requirements

  1. 支持常见数据类型:对象、数组、日期、正则等
    Support common data types: Object, Array, Date, RegExp
  2. 能正确处理循环引用(即对象引用自身或互相引用)
    Handle circular references properly
  3. 不使用 JSON 序列化的方法(如 JSON.stringify
    Do not use JSON.stringify or JSON.parse
  4. 保持纯函数风格,无副作用,不使用 this
    Use a pure functional style with no side effects and no use of this

参考答案 Reference Solution

function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== 'object') {
    return value;
  }

  if (seen.has(value)) {
    return seen.get(value); // 处理循环引用 Handle circular refs
  }

  let cloned;

  if (Array.isArray(value)) {
    cloned = [];
  } else if (value instanceof Date) {
    cloned = new Date(value);
  } else if (value instanceof RegExp) {
    cloned = new RegExp(value.source, value.flags);
  } else {
    cloned = {};
  }

  seen.set(value, cloned);

  for (const key in value) {
    if (value.hasOwnProperty(key)) {
      cloned[key] = deepClone(value[key], seen);
    }
  }

  return cloned;
}

示例 Example

const obj = {
  a: 1,
  b: { c: 2 },
  d: [3, 4],
  e: new Date(),
  f: /abc/g
};
obj.self = obj; // 循环引用 Circular reference

const copy = deepClone(obj);

console.log(copy.b === obj.b);       // false
console.log(copy.d === obj.d);       // false
console.log(copy.self === copy);     // true
console.log(copy.e.getTime() === obj.e.getTime()); // true
console.log(copy.f.source === obj.f.source);       // true

面试考察点 Interview Focus

  • 对递归、对象类型判断的掌握
    Mastery of recursion and object type detection
  • 对边界场景的处理能力(循环引用、特殊对象等)
    Ability to handle edge cases like circular references and special object types
  • 使用 WeakMap 等高阶数据结构解决问题的能力
    Using advanced structures like WeakMap to solve real-world issues