【问题标题】:Return Statement is not doing what I would have expectedReturn Statement 没有达到我的预期
【发布时间】:2021-10-15 20:32:23
【问题描述】:

这里是代码。

print(5);

function print(n) {
  if (n == 0) {
    return;
  }
  print(n - 1); //call function recursively  
  console.log(n);
}

我希望在 return 语句之后 console.log(n) 会输出零 (0),因为这是我调用 return 语句时 n 的值。相反,它返回 1 - 5 ??? Return 只调用了一次,所以谁能解释这里发生了什么?

【问题讨论】:

  • 最后一次递归调用是n = 1。结果,最后一次递归调用是:print(n - 1) --> print(1 - 1) --> print(0)。不打印零是因为当 n = 0 时,您从函数返回 - 在该函数调用中未达到 console.log
  • 嗨,Sam,如果我的回答有帮助,请随时接受答案。如果您想了解更多信息,请在评论中弹出,我会尽力详细说明。

标签: javascript function recursion


【解决方案1】:

print 函数仍然被调用了五次。 n 的值不会传播到之前的调用。

return 语句不会结束整个递归调用链。在调用退出函数的行中的 return 语句之后继续执行。

如果您希望某些代码在递归函数中只执行一次,请将其放在 if 分支中的 return 之前:

function print(n) {
  if (n == 0) {
    console.log(n);
    return;
  }
  print(n - 1); //call function recursively  
}

【讨论】:

    【解决方案2】:

    在你的代码中有一个隐式返回,把函数想象成这样:

    function print(n){
        if(n==0){
          return ;
        }  
        print(n-1); //call function recursively  
        console.log(n);
        return undefined;
      }
       
    

    所以当print(n-1)4 调用时,它会向下递归直到你得到0 的值。然而,在那之后,调用函数将记录n 值。

    基本上你的 return 只返回给调用者,它不会完全展开调用堆栈并防止 console.log 被调用。它看起来像这样:

    print(n-1); // called with 4
      print(n-1); // called with 3
        print(n-1); // called with 2
          print(n-1); // called with 1
            print(n-1); // called with 0
            return;
          console.log(n) // 1 
        console.log(n) // 2
      console.log(n) // 3
    console.log(n) // 4
    console.log(n) // 5
    

    【讨论】:

    • 感谢伊恩和樱桃木的帮助。我花了一段时间才深入了解您的答案,实际上我仍在阅读这个令人困惑的主题。隐藏的自动堆栈返回是一个难以掌握的概念,但我正在取得进展。保重:)
    猜你喜欢
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    相关资源
    最近更新 更多