在调用递归函数的初始函数中未定义

时间:2017-08-11 01:18:43

标签: javascript function recursion recursive-datastructures

我想知道是否有任何方法让我纠正我的代码,以便我可以将我需要的对象返回到我原来的调用函数。

onAccountSelected调用我的递归函数。有没有办法让我在我的初始调用函数 - onAccountSelected中进行最终匹配 - 从我的递归函数返回最终匹配?

我试过这个:

private findMatch(accountNodeName, currentNode) {
    if (currentNode.children) {
        for (var i = 0; i < currentNode.children.length; i++) {
            var current = currentNode.children[i];
            if (accountNodeName === current.name) {
                return current;
            }

            // return won't work here because I'm returning even if a match isn't found
            return this.findMatch(accountNodeName, current);                

             // this gives me undefined a bunch and then the actual answer once a match is found
            this.currentTreeNode = this.findMatch(accountNodeName, current);
            // console.log(this.currentTreeNode);
        }
    }
}

private onAccountSelected(account) {
  if (account.nodes) {
        this.currentTreeNode = this.findMatch(account.nodes.name, this.gridTreeNodes.BssNode);
        //getting undefined here, would like the matching node to come here
        console.log(this.currentTreeNode); //getting undefined here
    } 
}

0 个答案:

没有答案