javascript 递归函数的javascript返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10719480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:49:06  来源:igfitidea点击:

javascript return of recursive function

javascriptrecursionreturn

提问by MirrorMirror

Hate to open a new question for an extension to the previous one:

讨厌打开一个新问题来扩展上一个问题:

function ctest() {
    this.iteration = 0;
    this.func1 = function() {
        var result = func2.call(this, "haha");
        alert(this.iteration + ":" + result);
    }
    var func2 = function(sWord) {
        this.iteration++;
        sWord = sWord + "lol";
        if ( this.iteration < 5 ) {
            func2.call(this, sWord);
        } else {
            return sWord;
        }
    }
}

this returns iteration = 5 but result UNDEFINED ? how is that possible ? i explicitly return sWord. It should have returned "hahalollollollollol" and just for doublecheck, if i alert(sWord) just before the return sWord it displays it correctly.

这将返回迭代 = 5 但结果 UNDEFINED ?这怎么可能?我明确返回 sWord。它应该返回“hahalollollollollol”并且只是为了仔细检查,如果我在返回 sWord 之前警告(sWord)它会正确显示它。

回答by Quentin

You have to return all the way up the stack:

您必须一直返回堆栈:

func2.call(this, sWord);

should be:

应该:

return func2.call(this, sWord);

回答by Rich O'Kelly

You need to return the result of the recursion, or else the method implicitly returns undefined. Try the following:

您需要返回递归的结果,否则该方法隐式返回undefined. 请尝试以下操作:

function ctest() {
this.iteration = 0;
  this.func1 = function() {
    var result = func2.call(this, "haha");
    alert(this.iteration + ":" + result);
  }
  var func2 = function(sWord) {
    this.iteration++;
    sWord = sWord + "lol";
    if ( this.iteration < 5 ) {
        return func2.call(this, sWord);
    } else {
        return sWord;
    }
  }
}

回答by shareef

keep it simple :)

把事情简单化 :)

your code modified in JSFiddle

您在 JSFiddle 中修改的代码

iteration = 0;
func1();

    function  func1() {
        var result = func2("haha");
        alert(iteration + ":" + result);
    }

    function func2 (sWord) {
        iteration++;

        sWord = sWord + "lol";
        if ( iteration < 5 ) {
            func2( sWord);
        } else {

            return sWord;
        }

    return sWord;
    }

回答by alex

Your outer function doesn't have a returnstatement, so it returns undefined.

您的外部函数没有return语句,因此它返回undefined.