← 输入框|github.com|刷新
Skip to content

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

Open

Description

@wingmeng

题目:

请编写一个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);
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions