[英]return statement that returns nothing in recursion
I found this code about recursion online我在网上找到了这个关于递归的代码
function countDownRecursive(n) {
if (n <= 0) {
console.log('Hooray')
return
}
console.log(n)
countDownRecursive(n - 1)
}
I am really confused about this code, why does it console.log("Hooray") and then return nothing?我真的对这段代码感到困惑,为什么它 console.log("Hooray") 然后什么也不返回? Can you explain it to me?你能给我解释一下吗? Thank you so much.太感谢了。
you returned a null value, the function output type is void.您返回了 null 值,function output 类型为无效。 try this尝试这个
if (n <= 0) {
console.log('Hooray')
return n
}
return
in this context means you don't want to continue running the function (similar to break
in iterations).在这种情况下return
意味着您不想继续运行 function (类似于break
迭代)。
The above recursive function's logic can be converted to this below while
logic.上面的递归函数的逻辑可以转换为下面的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; }
why does it console.log("Hooray")为什么它 console.log("Hooray")
Because the function is recursive and when you start with let's say n=1
the function will not print "Hooray" immediately, because the condition:因为 function 是递归的,当你从n=1
开始时,function 不会立即打印“万岁”,因为条件:
if (n <= 0)
does not apply ie is false
.不适用 ie 是false
。
By the time we reach the recursion:当我们到达递归时:
countDownRecursive(n - 1)
We call the function again with n=0
due to n - 1
, the if-statement will evaluate to true
and therefore print "Hooray".我们再次调用 function 由于n - 1
而n=0
,if 语句将评估为true
,因此打印“万岁”。
and then return nothing然后什么也不返回
It does not actually return "nothing", even though the return type is void
, it returns undefined
, which is the default behavior for return
you could also write return undefined
instead.它实际上并没有返回“nothing”,即使返回类型是void
,它也会返回undefined
,这是return
的默认行为,您也可以改写return undefined
。
When you use return
, it will basically terminate or return from the current function.当你使用return
时,它基本上会从当前的 function 终止或返回。 It will jump back into the scope where you did call the function initially.它将跳回 scope,您最初在其中调用了 function。
Hope that clears it up for you.希望能为您解决问题。
Let's do it with an example.让我们举个例子。 This is the hierarchy of the calls when n = 5这是 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
The returns statement tells the program to stop calling itself return 语句告诉程序停止调用自己
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.