我正在尝试返回 JSON 对象结构中的特定节点,如下所示
{
"id":"0",
"children":[
{
"id":"1",
"children":[...]
},
{
"id":"2",
"children":[...]
}
]
}
所以这是一个树状的子父关系。每个节点都有一个唯一的ID。 我正在尝试找到一个像这样的特定节点
function findNode(id, currentNode) {
if (id == currentNode.id) {
return currentNode;
} else {
currentNode.children.forEach(function (currentChild) {
findNode(id, currentChild);
});
}
}
我通过 findNode("10", rootNode)
执行搜索。但即使搜索找到匹配项,该函数也始终返回 undefined
。我有一种不好的感觉,递归函数在找到匹配项后不会停止,并继续运行最终返回 undefined
因为在后面的递归执行中它没有到达返回点,但我不知道如何解决这个问题。
请帮忙!
最佳答案
递归搜索时,必须通过返回的方式将结果传回。不过,您没有返回 findNode(id, currentChild)
的结果。
function findNode(id, currentNode) {
var i,
currentChild,
result;
if (id == currentNode.id) {
return currentNode;
} else {
// Use a for loop instead of forEach to avoid nested functions
// Otherwise "return" will not work properly
for (i = 0; i < currentNode.children.length; i += 1) {
currentChild = currentNode.children[i];
// Search in the current child
result = findNode(id, currentChild);
// Return the result if the node has been found
if (result !== false) {
return result;
}
}
// The node has not been found and we have no more options
return false;
}
}
关于JavaScript 在 JSON 对象中递归搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22222599/