深拷贝循环引用的问题
来源:4-3 手写 JS 深拷贝

光天化日之下
2019-12-28
出现循环引用的时候会报错
index.js:23 Uncaught RangeError: Maximum call stack size exceeded
然后按照网上参考方案修改如下,并且想看看的老师的方案是怎样的:
/**
* 深拷贝
* @param {*} [obj={}] 要拷贝的对象
* @param {*} [hash=new WeakMap()] 哈希表存储已拷贝过的对象
* @returns
*/
function deepClone(obj = {}, hash = new WeakMap()) {
if (typeof obj !== 'object' || obj == null) {
// 不是引用类型或者null,直接返回
return obj
}
if (hash.has(obj)) return hash.get(obj);
// 初始化返回结果
let result = obj instanceof Array ? [] : {}
hash.set(obj, result);
// 数组和对象都可以使用for in遍历
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
// 保证key不是原型上的key
const element = obj[key];
// 递归调用
result[key] = deepClone(element, hash)
}
}
return result
}
写回答
2回答
-
做的很好,避免循环引用就是用 WeekMap
232021-06-13 -
RadiomM
2020-05-13
你这个写的是不是有问题呢? 为什么return的是 hash.get(obj) 你下面写入的不是一个空数组或者是一个空对象吗?
122020-05-14
相似问题