javascript返回递归函数

Mir*_*ror 12 javascript recursion return

讨厌为前一个扩展打开一个新问题:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会返回iteration = 5,但结果是UNDEFINED?怎么可能?我明确地返回了sWord.它应该返回"hahalollollollollol"并且仅用于双重检查,如果我在返回sWord之前警告(sWord)它正确地显示它.

Que*_*tin 24

你必须一直返回堆栈:

func2.call(this, sWord);
Run Code Online (Sandbox Code Playgroud)

应该:

return func2.call(this, sWord);
Run Code Online (Sandbox Code Playgroud)


Ric*_*lly 5

您需要返回递归的结果,否则方法会隐式返回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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)