我只是在尝试一些递归,并注意到让我感到困惑的一些事情。让我用一些代码示例来说明:
function loop(x){ if(x> = 10) 返回x; loop(x + 1); //递归调用} loop(0);上面的调用返回 undefined 。如果我将其更改为
函数循环(x){ if(x> = 10)返回x; 返回循环(x + 1); //递归调用} loop(0);然后它正确返回 10 。
为什么会这样? return 子句如何影响堆栈?
PS:类似的问题
编辑: 这是一张快速图片,概述了什么我明白了。 (我绝对没有油漆。)是不是?如果没有,我哪里出错了?
解决方案如果你没有从Javascript函数返回,最后会有一个隐含的return undefined。
函数循环(x){ if(x> = 10)返回x; loop(x + 1); //递归调用返回undefined; }正如您所见,正在调用递归调用并具有其返回值忽略。这就像调用像 console.log 这样的函数时发生的情况 - 函数被调用并运行任何副作用,但最后会丢弃返回值。 / p>
I was just experimenting with some recursion and noticed something that confused me. Let me illustrate with some code examples:
function loop(x) { if (x >= 10) return x; loop(x + 1); // the recursive call } loop(0);The call above returns undefined. If I change it to
function loop(x) { if (x >= 10) return x; return loop(x + 1); // the recursive call } loop(0);then it returns 10 correctly.
Why does this happen? How does the return clause affect the stack?
PS: Similar question
EDIT: Here's a quick image outlining what I've understood. (I have absolutely no paint-fu.) Is it right? If not, where have I gone wrong?
解决方案If you don't return from a Javascript function there is an implicit "return undefined" in the end.
function loop(x) { if (x >= 10) return x; loop(x + 1); // the recursive call return undefined; }As you can see, te recursive call is being called and having its return value ignored. This is just like what happens when you call a function like console.log - the function gets called and runs any side-effects but you discard the return value in the end.
更多推荐
在递归函数调用之前使用return子句与不使用return子句有何不同?
发布评论