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));
关于javascript - JavaScript 中的递归出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39103214/