Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

题目:

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

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

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.