我正在尝试返回 JSON 对象结构中的特定节点,如下所示
{
"id":"0",
"children":[
{
"id":"1",
"children":[...]
},
{
"id":"2",
"children":[...]
}
]
}
所以这是一个树状的子父关系。每一个node有一个唯一的ID。
我正在尝试寻找一个具体的node像这样
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)