Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
910 views
in Technique[技术] by (71.8m points)

recursion - Simple Recursive Javascript Function Returns Undefined

For an assignment I am supposed to write a recursive function that checks any integer for even or odd using N-2. If even returns true else returns false. But it returns undefined whenever a value is large enough to call itself. Please help!

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));
// → ??

Console Log Results:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have forgotten the return statement before the recursive isEven(num) call.

See the snippet below:

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...