我正在处理一个递归函数,它返回的值似乎比预期的错误。我能够复制它并将函数简化为:
function foo(i, target){
if(i < target){
i++;
foo(i, target);
}
return i;
}
console.log(foo(0,5));
基本上,鉴于上面的函数,我希望返回值为 5。但是,它似乎返回 1。当我进行一些跟踪时,我注意到“return i”被调用了几次,每次它都得到减1?这种行为的原因是什么?我该如何解决?
最佳答案
您还需要从 if
返回加入您的代码。
function foo(i, target){
if(i < target){
i++;
return foo(i, target);
}
console.log(i);
return i;
}
console.log(foo(0,5));
为什么您的代码返回 1?
因为它只调用了 foo
每次 i < target
在它之后,您将按 5, 4, 3, 2, 1
顺序获得从嵌套调用返回的所有值最后一个从第一个函数调用返回的被打印出来。您可以通过输入简单的 console.log
来检查这一点在 return i
之前并与上述结果进行比较。
function foo(i, target){
if(i < target){
i++;
foo(i, target);
}
console.log(i);
return i;
}
console.log(foo(0,5));
可视化你可以看到的返回值
console.log() console.log()
| Call with 1 -- return Call with 1
| | Call with 2 -- return Call with 2
| | | Call with 3 -- return Call with 3
| | | | Call with 4 -- return Call with 4
| | | | | Call with 5 VS -- return Call with 5
| | | | | return 5
| | | | return 4
| | | return 3
| | return 2
|-- return 1
关于javascript递归返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47590418/