对于一个任务,我应该写一个递归函数,检查使用N-2的任何整数的偶数或奇数。如果甚至返回true,否则返回false。但是只要一个值足够大就可以调用自己,它就会返回undefined。请帮忙!简单的递归Javascript函数返回未定义
function isEven(num) {
console.log("top of function num = " + num);// For Debugging
if (num == 0){
return true;
}
else if (num == 1){
return false;
}
else {
num -= 2;
console.log("num = " + num);
isEven(num);
}
}
console.log(isEven(0));
// → true
console.log(isEven(1));
// → false
console.log(isEven(8));
// → ??
控制台登录结果:
top of function num = 0
true
top of function num = 1
false
top of function num = 8
num = 6
top of function num = 6
num = 4
top of function num = 4
num = 2
top of function num = 2
num = 0
top of function num = 0
undefined
你''中从未isEven'返回一个值else'情况。 –
其他人确实需要返回一个值! – Robba
伟大的功课教你使用递归功能的错误方法。改用模数。 – Xorifelse