在JavaScript中检测和修复循环引用 [英] Detecting and fixing circular references in JavaScript
问题描述
鉴于我在大型JavaScript对象中有循环引用
Given I have a circular reference in a large JavaScript object
我尝试 JSON.stringify(problematicObject)
浏览器抛出
TypeError:将循环结构转换为JSON
"TypeError: Converting circular structure to JSON"
(预期)
然后我想找到本循环参考的原因,最好使用Chrome开发人员工具?这可能吗?如何在大型对象中查找和修复循环引用?
Then I want to find the cause of this circular reference, preferably using Chrome developer tools? Is this possible? How do you find and fix circular references in a large object?
推荐答案
从 http://blog.vjeux.com/2011/javascript/cyclic-object-detection.html 。添加一行以检测循环的位置。将其粘贴到Chrome开发工具中:
Pulled from http://blog.vjeux.com/2011/javascript/cyclic-object-detection.html. One line added to detect where the cycle is. Paste this into the Chrome dev tools:
function isCyclic (obj) {
var seenObjects = [];
function detect (obj) {
if (obj && typeof obj === 'object') {
if (seenObjects.indexOf(obj) !== -1) {
return true;
}
seenObjects.push(obj);
for (var key in obj) {
if (obj.hasOwnProperty(key) && detect(obj[key])) {
console.log(obj, 'cycle at ' + key);
return true;
}
}
}
return false;
}
return detect(obj);
}
以下是测试:
> a = {}
> b = {}
> a.b = b; b.a = a;
> isCyclic(a)
Object {a: Object}
"cycle at a"
Object {b: Object}
"cycle at b"
true
这篇关于在JavaScript中检测和修复循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!