Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue Jun 16, 2019 · 0 comments
Open

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

wingmeng opened this issue Jun 16, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jun 16, 2019

题目:

请编写一个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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant