简单的递归Javascript函数返回未定义 [英] Simple Recursive Javascript Function Returns Undefined

查看:41
本文介绍了简单的递归Javascript函数返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个赋值,我应该编写一个递归函数,该函数使用N-2检查任何整数是否为偶数或奇数.如果甚至返回true,则返回false.但是,只要值大到足以调用它自己,它就会返回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));
// → ??

控制台日志结果:

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(num)调用之前,您已经忘记了 return 语句.

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

请参见下面的代码段

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

这篇关于简单的递归Javascript函数返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆