[英]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
和调试器,我可以看到以下内容:
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)
,它将通过以下执行步骤:
fib(1)
fib(1)
fib(2)
fib(2)
0 + 1
0 + 1
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.