开发者问题收集

JavaScript 中递归出错

2016-08-23
33
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 错误,但我想要数字的总和。我哪里犯了错误?

3个回答

在最后一次迭代中,您正确地检查了输入是否为 <= 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));
TimoStaudinger
2016-08-23

尝试

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));
maxeh
2016-08-23
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));

之前没有终止递归的语句

akitsme
2016-08-23