繁体   English   中英

递归函数的javascript返回

[英]javascript return of recursive function

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

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;
        }
    }
}

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

您必须一直返回堆栈:

func2.call(this, sWord);

应该:

return func2.call(this, sWord);

您需要返回递归的结果,否则该方法隐式返回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;
    }
  }
}
 func2.call(this, sWord);

应该

return func2.call(this, sWord);

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

把事情简单化 :)

您在 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;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM