gpt4 book ai didi

javascript - 如何检测 JavaScript 中的循环引用

转载 作者:搜寻专家 更新时间:2023-10-31 23:26:18 25 4
gpt4 key购买 nike

例如:

$ node
> var x = {}
undefined
> x.x = x
{ x: [Circular] }

想知道他们使用何种结构来完成此操作,因为它没有直接编码到我刚刚所做的事情中。似乎他们会做类似的事情:

var graph = new Graph(object)
graph.detectCircularReferences()

然后它会得到它们,但不确定它是如何工作的。希望学习如何实现。

最佳答案

考虑到评论中的想法,我来到了这个功能。它遍历传递的对象(通过数组和对象)并返回指向循环引用的路径数组。

// This function is going to return an array of paths
// that point to the cycles in the object
const getCycles = object => {
if (!object) {
return;
}

// Save traversed references here
const traversedProps = new Set();
const cycles = [];

// Recursive function to go over objects/arrays
const traverse = function (currentObj, path) {
// If we saw a node it's a cycle, no need to travers it's entries
if (traversedProps.has(currentObj)) {
cycles.push(path);
return;
}

traversedProps.add(currentObj);

// Traversing the entries
for (let key in currentObj) {
const value = currentObj[key];
// We don't want to care about the falsy values
// Only objects and arrays can produce the cycles and they are truthy
if (currentObj.hasOwnProperty(key) && value) {
if (value.constructor === Object) {
// We'd like to save path as parent[0] in case when parent obj is an array
// and parent.prop in case it's an object
let parentIsArray = currentObj.constructor === Array;
traverse(value, parentIsArray ? `${path}[${key}]` : `${path}.${key}`);

} else if (value.constructor === Array) {
for (let i = 0; i < value.length; i += 1) {
traverse(value[i], `${path}.${key}[${i}]`);
}
}

// We don't care of any other values except Arrays and objects.
}
}
}

traverse(object, 'root');
return cycles;
};

然后你可以这样测试:

// Making some cycles.
const x = {};
x.cycle = x;
const objWithCycles = {
prop: {},
prop2: [1, 2, [{subArray: x}]]
};
objWithCycles.prop.self = objWithCycles;

console.log(getCycles(objWithCycles));

它产生以下输出,它是对象中循环的列表:

[ 'root.prop.self', 'root.prop2[2][0].subArray.cycle' ]

关于javascript - 如何检测 JavaScript 中的循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47917417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com