[英]A simplest recursive function returns undefined
Code: 码:
function forLoop(x) {
if (x >= 10) {
console.log(x); // here if I add console.log(x) , x value is 10
return (x); // next line if i return x output = undefined
}
forLoop(x + 1);
}
console.log(forLoop(0));
The output is "undefined" instead of 10. 输出为“未定义”,而不是10。
Can anyone explain how recursion works in detail and how to fix the bug in my code? 谁能解释递归的工作原理以及如何修复我的代码中的错误?
If x is greater or equal to 10, the function returns x. 如果x大于或等于10,则函数返回x。
Otherwise, it calls itself but returns nothing . 否则,它会自行调用, 但不返回任何内容 。
You have to return something when the if
fails. if
失败, if
必须返回某些内容。
function forLoop(x) {
if (x >= 10) {
return (x);
}
return forLoop(x + 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.