我正在完成第 1 章的第一个练习。 4 Eloquent JavaScript。 以下是我迄今为止所做的两个功能。
//Takes two number parameters and outputs the range into an array.
var rangeArray = [];
function range(start, end) {
for (var i = start; i <= end; ++i)
rangeArray.push(i);
return rangeArray;
}
//Takes the array from above and is supposed to output the sum of the elements of the array.
function sum(range) {
var sumTotal = 0;
for (var index = 0; index <= rangeArray.length; ++index)
sumTotal += rangeArray[index];
return sumTotal;
}
//The above functions are supposed to output the outputs shown below if they work correctly. The first one works, but the second console.log statement gives me an output of NaN.
console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(sum(range(1, 10)));
// → 55
所以,我的第二个函数出了问题,但我不知道出什么问题。是初始参数(范围)吗?或者某处有语法错误?
这是我从中获取这些练习的页面的链接,它们位于页面底部附近。 http://eloquentjavascript.net/04_data.html
非常感谢您的帮助!
最佳答案
您的 for
超出了数组的长度,因此它尝试将 undefined
添加到 sumTotal
因此 NaN
.
关于javascript - 函数的输出 = NAN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34969369/