繁体   English   中英

在递归中不返回任何内容的 return 语句

[英]return statement that returns nothing in recursion

我在网上找到了这个关于递归的代码

function countDownRecursive(n) {
  if (n <= 0) {
    console.log('Hooray')
    return
  }

  console.log(n)
  countDownRecursive(n - 1)
}

我真的对这段代码感到困惑,为什么它 console.log("Hooray") 然后什么也不返回? 你能给我解释一下吗? 太感谢了。

您返回了 null 值,function output 类型为无效。 尝试这个

if (n <= 0) {
    console.log('Hooray')
    return n
  }

在这种情况下return意味着您不想继续运行 function (类似于break迭代)。

上面的递归函数的逻辑可以转换为下面的while逻辑。

 let n = 3; //iterate until found the while break while (true) { //the condition to stop if (n <= 0) { console.log('Hooray'); break; //stop `while` } console.log(n) n = n - 1; }

为什么它 console.log("Hooray")

因为 function 是递归的,当你从n=1开始时,function 不会立即打印“万岁”,因为条件:

if (n <= 0)

不适用 ie 是false

当我们到达递归时:

countDownRecursive(n - 1)

我们再次调用 function 由于n - 1n=0 ,if 语句将评估为true ,因此打印“万岁”。

然后什么也不返回

它实际上并没有返回“nothing”,即使返回类型是void ,它也会返回undefined ,这是return的默认行为,您也可以改写return undefined

当你使用return时,它基本上会从当前的 function 终止或返回。 它将跳回 scope,您最初在其中调用了 function。

希望能为您解决问题。

让我们举个例子。 这是 n = 5 时调用的层次结构

countDownRecursive(5) // "5"
  countDownRecursive(4) // "4"
    countDownRecursive(3) // "3"
      countDownRecursive(2) // "2"
        countDownRecursive(1) // "1"
          countDownRecursive(0) // "Hooray" because n == 0, we execute the return statement
          end of countDownRecursive(0) because of return
        end of countDownRecursive(1) because reaching the end
      end of countDownRecursive(2) because reaching the end
    end of countDownRecursive(3) because reaching the end
  end of countDownRecursive(4) because reaching the end
end of countDownRecursive(5) because reaching the end

return 语句告诉程序停止调用自己

暂无
暂无

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

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