在递归函数javascript上获取未定义的返回值 [英] Getting return undefined on recursive function javascript

查看:53
本文介绍了在递归函数javascript上获取未定义的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说递归函数很强大,所以我尝试创建一个函数来增加一个数字,直到它达到某些点,而不是通过循环.当它到达时,我试图返回该值,但它给出 undefined.

I heard recursive function is powerful so instead going through loop i tried to create a function which increments a number until it reach certain points. when it reaches i tried to return the value, but it give undefined.

代码

var i=1;
function rec(){
    i++;
    console.log(i);
    if(i > 100){
        return i;
    }else{
        rec();
    }
}

console.log(rec());

这里 i 递增到 100.但在限制之后返回 undefined.为什么会这样?另外请让我知道,这种递归是好的,然后 for 循环?

Here the i is incrementing until 100. but it returns undefined after the limit. Why is this happening? Also please let me know, it this kind of recursion is good then for loop?

推荐答案

vaultah 的评论是正确的:

The comment by vaultah is correct:

var i=1;
function rec(){
    i++;
    console.log(i);
    if(i > 100){
        return i;
    }else{
        return rec();
    }
}

snippet.log(rec());

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

举个例子,只计算>5 并添加一些输出,以便您可以更轻松地查看发生的情况(但同样,使用调试器单步执行代码是查看其工作原理的正确方法):

Let's take an example that only counts to > 5 and add some output so you can see what happens more easily (but again, stepping through the code with a debugger is the right way to see how this works):

var indent = "";
var i=1;
function rec(){
    var rv;
    i++;
    indent += "&nbsp;";
    if(i > 5){
      snippet.logHTML("<p>" + indent + i + " > 5, returning " + i + "</p>");
        rv = i;
    }else{
        snippet.logHTML("<p>" + indent + i + " is not > 5, calling rec</p>");
        rv = rec();
        snippet.logHTML("<p>" + indent + "Got " + rv + " back from rec, returning it</p>");
    }
    indent = indent.substring(0, indent.length - 6);
    return rv;
}

snippet.logHTML("<p>Final result: " + rec() + "</p>");

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

这篇关于在递归函数javascript上获取未定义的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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