2016-08-23 34 views
0

得到錯誤的遞歸在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

回答

1

在您最後一次迭代中,你正確地檢查輸入是否<= 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

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

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

沒有終止語句遞歸早期