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

实现深拷贝 #102

Open
lovelmh13 opened this issue Jul 5, 2021 · 0 comments
Open

实现深拷贝 #102

lovelmh13 opened this issue Jul 5, 2021 · 0 comments

Comments

@lovelmh13
Copy link
Owner

不考虑循环引用的版本

function deepCopy(item) {
  if (typeof item === 'object') {
    const obj = Array.isArray(item) ? [] : {}
    for (const key in item) {
      obj[key] = deepCopy(item[key])
    }
    return obj
  } else {
    return item
  }
}

// 测试
var a = {
  b: 1,
  c: 2,
  d: {
    e: 3
  }
}
const a_copy = deepCopy(a)
console.log(a_copy)

解决循环引用

思路,开辟一个新的内存存放对象,拷贝对象的时候去那个地方找,有的话就返回那个对象,没有的话就创建一个

function deepCopy(item, map = new Map()) {
  if (typeof item === 'object') {
    const obj = Array.isArray(item) ? [] : {}
    if (map.get(item)) {
      return map.get(item)
    }
    map.set(item, obj)
    for (const key in item) {
      obj[key] = deepCopy(item[key], map)
    }
    return obj
  } else {
    return item
  }
}

// 测试
const target = {
  field1: 1,
  field2: undefined,
  field3: {
    child: 'child'
  },
  field4: [2, 4, 8]
}
target.target = target
const a_copy = deepCopy(target)
console.log(a_copy)
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