简体   繁体   English

遍历数组并使用JS汇总所有值

[英]iterate over an array and sum up all values with JS

as the title says i'm trying to sum up using a for loop to iterate over an array. 如标题所述,我正在尝试使用for循环来总结一个数组。 can you give me some pointers as to where i'm going wrong here. 您能给我一些有关我在哪里出错的指示吗? i am returning the value NaN. 我返回值NaN。

var total = 0;

function sum(input) {
    for (idx=0; idx<=input; idx++) {
        total += input[idx];
    }
    return total;
}

You actually don't need a loop to do this in modern browsers, you can use the Array.reduce function: 实际上,在现代浏览器中,您不需要循环即可执行此操作,可以使用Array.reduce函数:

var sum = input.reduce(function(a,b){
    return a+b;
}, 0);

You need ot declare total into function and also you need to declare idx. 您需要在函数中声明ot,还需要声明idx。 Another thing that instead of writing idx <= input.length you have to write idx <= input.length - 1 . 另一件事是,必须编写idx <= input.length - 1而不是编写idx <= input.length Since last index will be undefined. 由于最后一个索引将是不确定的。

Try 尝试

function sum(input) {
    total = 0;
    for (var idx = 0; idx <= input.length - 1; idx++) {
        total += input[idx];
    }
    return total;
}

variable total is not declared! 未声明变量total

function sum(input) {
    var total = 0;
    for (idx=0; idx <= input.length; idx++) {
        total += input[idx];
    }
    return total;
}

Problem which result in NaN is because of your array traversing array till end, rather than from indices 0 to input.length-1 Try this: http://jsfiddle.net/t9tfofxv/ 导致NaN问题是由于数组遍历数组直到结束,而不是从索引0input.length-1请尝试以下操作: http : //jsfiddle.net/t9tfofxv/

var total = 0;
function sum(input) {
for (var idx=0; idx< input.length; idx++) {
    total += input[idx];
}
return total;
}
var s=sum([1,2,3,4]);
alert(s);

Declare the variable total inside the function, and also use input.length-1 to define the loop's range: 在函数内部声明变量total,并使用input.length-1定义循环的范围:

function sum(input) {
    var total = 0;
    for (idx=0; idx <= input.length-1; idx++) {
        total += input[idx];
    }
    return total;
}

You are using input both as an integer, and as an array of values. 您将input同时用作整数和值数组。 Probably you mean for( var idx = 0; idx < input.length; ++idx )... . 也许你的意思是for( var idx = 0; idx < input.length; ++idx )...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM