在JavaScript中递归时出错

getting error on recursion in JavaScript

本文关键字:出错 递归 JavaScript      更新时间:2023-09-26

var summation = function(num) {
  if (num <= 0) {
    console.log("number should be greater than 0");
  } else {
    return (num + summation(num - 1));
  }
};
console.log(summation(5));

它给了我一个NaN错误,但我想求和。我在哪里搞错了?

在上一次迭代中,您正确地检查了输入是否为<= 0,但随后什么都不返回,这导致了undefined的隐式返回值。

undefined添加到数字会导致NaN:

console.log(1 + undefined); // NaN

要解决此问题,如果您的取消条件已被满足,请返回0

var summation = function(num) {
  if (num <= 0) {
    console.log("number should be greater than 0");
    return 0;
  } else {
    return (num + summation(num - 1));
  }
};
console.log(summation(5));

尝试

var summation = function (num) {
  if(num <=0){
    console.log("number should be greater than 0");
    return 0;
  }
  else{
    return(num + summation(num-1));
  }
};
console.log(summation(5));

var summation = function (num) {
  if(num <=0){
  console.log("number should be greater than 0");
  return(0);
  }else{
  return(num + summation(num-1));
 }
};
console.log(summation(5));

早期的没有终止递归语句