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

实现深拷贝 #33

Open
sihai00 opened this issue Aug 4, 2019 · 0 comments
Open

实现深拷贝 #33

sihai00 opened this issue Aug 4, 2019 · 0 comments
Assignees

Comments

@sihai00
Copy link
Owner

sihai00 commented Aug 4, 2019

实现深拷贝

浅拷贝只拷贝一层,对复杂数据类型存在引用问题,所以需要层层拷贝即深拷贝。

JSON

JSON.parse(JSON.stringify(obj))

存在缺点:

  1. undefined:忽略
  2. 函数:忽略
  3. Date:不正确
  4. RegExp:不正确
  5. Symbol:忽略
  6. 原型链:忽略
var a = {
	a: undefined,
	b: function(){},
	c: new Date(),
	d: new RegExp(),
	e: Symbol('a')
}
JSON.parse(JSON.stringify(a))

// 结果
//{
//  c: "2019-08-04T14:14:57.946Z",
//  d: {}
//}

实现深拷贝

function is(value, type){
  return Object.prototype.toString.call(value) === `[object ${type}]`
}
function deepClone(obj, hash = new WeakMap()) {
  if (is(obj, 'RegExp')) return new RegExp(obj) 
  if (is(obj, 'Date')) return new Date(obj)
  if (obj === null || typeof obj !== 'object') return obj
  if (hash.has(obj)) return hash.get(obj)
   
  var target = new obj.constructor()
  hash.set(obj, target)
  
  Reflect.ownKeys(obj).forEach(v => {
    if (is(obj[v], 'Object')) {
      target[v] = deepClone(obj[v], hash)
    } else {
      target[v] = obj[v]
    }
  }) 
  
  return target
}

var a = {
	a: undefined,
	b: function(){},
	c: new Date(),
	d: new RegExp(),
	e: Symbol('a'),
	f: {a: {b: 1}},
	g: [[1], [2], [3]]
}
var b = deepClone(a)

参考

【进阶4-3期】面试题之如何实现一个深拷贝
这儿有20道大厂面试题等你查收

@sihai00 sihai00 self-assigned this Aug 4, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant