在递归函数调用之前使用return子句与不使用return子句有何不同? [英] How does using a return clause before a recursive function call differ from not using one?

查看:151
本文介绍了在递归函数调用之前使用return子句与不使用return子句有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在尝试一些递归,并注意到让我感到困惑的一些事情。让我用一些代码示例来说明:

  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子句有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆