得到错误的递归在JavaScript
问题描述:
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的错误,但我想number.where我是会犯错的总和?
答
在您最后一次迭代中,你正确地检查输入是否<= 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));
+0
感谢它的工作了,我也拿到了我的错误:) – sanket
答
尝试
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));
+0
它的工作现在,由于:) – sanket
答
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));
没有终止语句递归早期
@blex感谢,它的工作原理:) – sanket