简体   繁体   English

为什么我的递归函数不返回最终结果?

[英]Why isn't my recursive function returning the final result?

I have a method which traverses an nested object recursively until it finds a matching folder name: 我有一种方法可以递归遍历嵌套对象,直到找到匹配的文件夹名称:

findSpecifiedFolder(data) {
    const bookmarks = JSON.parse(data).roots.bookmark_bar.children;
    const search = bookmarks => {
        for(let folder of bookmarks) {
            const folderName = folder.name.toLowerCase();
            if(folderName === folderArg.toLowerCase()) {
                console.log(folder); // returns folder object
                return folder // never returns anything
            }
            else if(folder.children) {
                search(folder.children);
            }
        }
    };
    search(bookmarks);
}

So by using console.log and my debugger I can see the following: 因此,通过使用console.log和调试器,我可以看到以下内容:

  1. The method does, in fact recursively search the given object, nested at least 3 levels deep. 实际上,该方法确实以递归方式搜索了至少嵌套三层的给定对象。
  2. I can confirm that I do in fact have a successful check when if(folderName === folderArg.toLowerCase()) gets executed both via the console.log statement and the data in the debugger 我可以确认我是否确实成功地通过console.log语句和调试器中的数据执行了if(folderName === folderArg.toLowerCase())检查

However, the return statement isn't getting executed (confirmed with debugger) and the method returns undefined (or an error when I called by another method with error logging). 但是,return语句未执行(已通过调试器确认),并且该方法返回未定义的(或当我由另一个带有错误日志记录的方法调用时返回错误)。 I no idea why so here I am asking if anyone might see some mistake in the method that I am missing. 我不知道为什么,所以我在这里问是否有人会在我缺少的方法中看到一些错误。

You have to return the recursive call, or else the returned value will not be delegated and returned when all recursive calls are resolved: 您必须返回递归调用,否则在解析所有递归调用时将不委托并返回返回值:

else if(folder.children) {
    return search(folder.children);
}

A simple proof of concept is the Fibonacci sequence. 一个简单的概念证明就是斐波那契数列。 Here's some pseudocode (without return): 这是一些伪代码(不返回):

function fib(n) {
    if n is 1 return 0;
    else if n is 2 return 1;
    else fib(n - 1) + fib(n - 2);
}

So if I call fib(2) , it will go through the following execution steps: 因此,如果我调用fib(2) ,它将通过以下执行步骤:

  1. Go to else 去别的
  2. Call fib(1) 致电fib(1)
  3. Return 0 返回0
  4. Call fib(2) 致电fib(2)
  5. Return 1 返回1
  6. Add 0 + 1 0 + 1
  7. Then do nothing. 然后什么都不做。 The code is basically else 1; 该代码基本上是else 1; which is an expression (the 1 part) and does nothing. 这是一个表达式(第1部分),什么也不做。

Since there is no return , the final result is computed, but you do nothing with it and the function returns undefined. 由于没有return ,因此将计算最终结果,但是您不对其进行任何操作,并且该函数返回undefined。 You have to return it. 您必须退货 The same principle applies here. 同样的原则在这里适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM