JSON对象中的JavaScript递归搜索
我试图返回一个像这样的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。我有一种不好的感觉,即递归函数在找到匹配项后不会停止并继续运行finally返回,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;
    }
}
以上是 JSON对象中的JavaScript递归搜索 的全部内容, 来源链接: utcz.com/qa/421661.html
