对于赋值,我应该编写一个递归函数,使用N-2检查偶数或奇数的任何整数。如果even返回true,则返回false。但是只要值足够大就可以调用自身,它就会返回undefined。请帮忙!
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
答案 0 :(得分:3)
您在递归return
来电之前忘记了isEven(num)
声明。
请参阅下面的代码:
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;
return isEven(num);
}
}
console.log('0 is even: ', isEven(0));
// → true
console.log('1 is even: ', isEven(1));
// → false
console.log('8 is even: ', isEven(8));
答案 1 :(得分:0)
您可以更改以下行:
isEven(num);
到
return isEven(num);