javascript - 函数的输出 = NAN

标签 javascript arrays function sum

我正在完成第 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/

相关文章:

javascript - 如何从 $.get() 函数内部编辑由 anchor 触发的事件?

javascript - 在 Aurelia.js 上离开页面之前如何要求用户确认

c++ - 不同来源的QT调用函数

c++ - 在 C++ 中使用 erase from vector 的一些问题

jquery - 如果 jquery 中的类名更改,则删除函数

PHP:将函数范围限制在当前文件内

javascript - 多个 node-mongodb-native 连接

javascript - 如何使用 jQuery 将两个 select 元素附加到表行?

javascript - 使用 lodash 从对象属性和值的集合创建两个数组

PHP 字符串直接访问使用 str[index] vs 拆分成一个数组