fezaoduke / fe-practice-hard

晚练课

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

第 34 期(W3C 标准-ECMAScript-语法):js 对象深拷贝

wingmeng opened this issue · comments

题目:

请编写一个js对象深拷贝的函数,需要考虑循环引用的情况。


参考答案:

function deepCopy(obj) {
  // hash表,记录所有的对象的引用关系
  let map = new WeakMap();

  function dp(obj) {
    let result = null;
    let keys = Object.keys(obj);
    let key = null,
      temp = null,
      existobj = null;
 
    existobj = map.get(obj);

    // 如果这个对象已经被记录则直接返回
    if (existobj) {
      return existobj;
    }
 
    result = {}
    map.set(obj, result);
 
    for (let i = 0; i < keys.length; i++) {
      key = keys[i];
      temp = obj[key];

      if (temp && typeof temp === 'object') {
        result[key] = dp(temp);
      }else {
        result[key] = temp;
      }
    }

    return result;
  }

  return dp(obj);
}