最简单的深拷贝(解决循环引用)

62 阅读1分钟

深拷贝 js 代码:

const cache = new Map();

function deepClone(value: any) {
  // 非对象直接返回值 
  //(undefined, null, number, string, boolean, function, Symbol, bigInt)
  if (typeof value !== "object" || value === null) {
    return value;
  }

  // 循环引用返回cloned
  if (cache.has(value)) {
    return cache.get(value);
  }

  // 创建cloned(object 或 array)
  const cloned = Array.isArray(value) ? [] : {};
  cache.set(value, cloned);

  // 遍历复制 object 或 array
  for (const key of Object.keys(value)) {
    cloned[key] = deepClone(value[key]);
  }

  return cloned;
}

测试代码:

const a = { name: 'a' }
const b = { name: 'b' }
a.next = b;
b.next = a;
const cloneB = deepClone(b);

console.log('zz -> ', cloneB == cloneB.next.next); // true
console.log('zz -> ', cloneB.next == cloneB.next.next.next); // true