得到错误的递归在JavaScript

问题描述:

得到错误的递归在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

@blex感谢,它的工作原理:) – sanket

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

没有终止语句递归早期