在递归函数调用之前使用return子句与不使用return子句有何不同?

编程入门 行业动态 更新时间:2024-10-24 22:26:54
本文介绍了在递归函数调用之前使用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子句有何不同?

本文发布于:2023-11-30 21:09:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651479.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子句   递归   函数   有何不同   return

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!