获得徽章 0
- 有个关于js深拷贝处理循环引用的问题我不是很明白,代码如下:
function deepCopy (obj, cache = []) {
function find (list, f) {
return list.filter(f)[0]
}
if (obj === null || typeof obj !== 'object') {
return obj
}
const hit = find(cache, c => c.original === obj)
if (hit) {
return hit.copy
}
const copy = Array.isArray(obj) ? [] : {}
cache.push({
original: obj,
copy
})
Object.keys(obj).forEach(key => {
copy[key] = deepCopy(obj[key], cache)
})
return copy
}
当key='circular',会触发find函数得到hit,返回的hit.copy={a:1},也就是说copy[circular]={a:1},但是我在运行的时候copy[circular]={a:1,circular:{..}},有人能为我讲讲为啥,运行截图如下展开评论点赞