最简单的递归函数返回undefined [英] A simplest recursive function returns undefined
本文介绍了最简单的递归函数返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
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));
输出为未定义而不是10。
The output is "undefined" instead of 10.
任何人都可以详细解释递归的工作原理以及如何修复我的代码中的错误吗?
Can anyone explain how recursion works in detail and how to fix the bug in my code?
推荐答案
如果x是大于或等于10,函数返回x。
If x is greater or equal to 10, the function returns x.
否则,它自称但不返回任何内容。
如果
失败,你必须退货。
You have to return something when the if
fails.
function forLoop(x) {
if (x >= 10) {
return (x);
}
return forLoop(x + 1);
}
这篇关于最简单的递归函数返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文