在 JavaScript 中对数组中的值求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16057672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:06:04  来源:igfitidea点击:

Sum values from an Array in JavaScript

javascriptarraysfor-loopsum

提问by Daniela costina Vaduva

I have defined a JavaScript variables called myDatawhich is a new Arraylike this:

我定义了一个名为的 JavaScript 变量myDatanew Array如下所示:

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

I am wondering if it is possible to sum the number values found in the array (ex. 0+0+21+2+0 and so on) and have probably a variable with the result that I can use outside of the script tag because I have 7 of this kind of arrays corresponding for each of the day in the week. I want to make a comparison afterwards based on that. That is the most preferred method for this kind of actions if is possible?

我想知道是否可以对数组中找到的数值求和(例如 0+0+21+2+0 等),并且可能有一个变量,我可以在脚本标记之外使用结果,因为我有 7 个这种数组对应于一周中的每一天。我想在此基础上进行比较。如果可能的话,这是此类操作的最首选方法吗?

采纳答案by Mark Walters

Try the following

尝试以下

var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];

var myTotal = 0;  // Variable to hold your total

for(var i = 0, len = myData.length; i < len; i++) {
    myTotal += myData[i][1];  // Iterate over your first array and then grab the second element add the values up
}

document.write(myTotal); // 22 in this instance

回答by KooiInc

You could use the Array.reducemethod:

您可以使用以下Array.reduce方法:

const myData = [
  ['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
  ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
  ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
  ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]
];
const sum = myData
  .map( v => v[1] )                                
  .reduce( (sum, current) => sum + current, 0 );
  
console.log(sum);

See MDN

MDN

回答by ruhanbidart

I think the simplest way might be:

我认为最简单的方法可能是:

values.reduce(function(a, b){return a+b;})

回答by Xotic750

I would use reduce

我会使用减少

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0], ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

var sum = myData.reduce(function(a, b) {
    return a + b[1];
}, 0);

$("#result").text(sum);

Available on jsfiddle

jsfiddle可用

回答by lee penkman

Creating a sum method would work nicely, e.g. you could add the sum function to Array

创建 sum 方法会很好地工作,例如您可以将 sum 函数添加到 Array

Array.prototype.sum = function(selector) {
    if (typeof selector !== 'function') {
        selector = function(item) {
            return item;
        }
    }
    var sum = 0;
    for (var i = 0; i < this.length; i++) {
        sum += parseFloat(selector(this[i]));
    }
    return sum;
};

then you could do

那么你可以做

> [1,2,3].sum()
6

and in your case

在你的情况下

> myData.sum(function(item) { return item[1]; });
23

Edit: Extending the builtins can be frowned upon because if everyone did it we would get things unexpectedly overriding each other (namespace collisions). you could add the sum function to some module and accept an array as an argument if you like. that could mean changing the signature to myModule.sum = function(arr, selector) {then thiswould become arr

编辑:扩展内置函数可能会令人皱眉,因为如果每个人都这样做,我们会意外地相互覆盖(命名空间冲突)。如果您愿意,您可以将 sum 函数添加到某个模块并接受一个数组作为参数。这可能意味着将签名更改为myModule.sum = function(arr, selector) {thenthis将变为arr

回答by Jan Jar?ík

Or in ES6

或者在 ES6 中

values.reduce((a, b) => a + b),

values.reduce((a, b) => a + b),

example:

例子:

[1,2,3].reduce((a, b)=>a+b) // return 6

回答by btk

If you want to discard the array at the same time as summing, you could do (say, stackis the array):

如果你想在求和的同时丢弃数组,你可以这样做(比如stack是数组):

var stack = [1,2,3],
    sum = 0;
while(stack.length > 0) { sum += stack.pop() };

回答by bjhamltn

You can use the native map method for Arrays. map Method (Array) (JavaScript)

您可以对数组使用本机 map 方法。 映射方法(数组)(JavaScript)

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);
var a = 0;
myData.map( function(aa){ a += aa[1];  return a; });

a is your result

a 是你的结果

回答by Gismo Ranas

The javascript built-in reduce for Arrays is not a standard, but you can use underscore.js:

Arrays 的 javascript 内置 reduce 不是标准,但您可以使用 underscore.js:

var data = _.range(10);
var sum = _(data).reduce(function(memo, i) {return memo + i});

which becomes

变成

var sumMyData = _(myData).reduce(function(memo, i) {return memo + i[1]}, 0);

for your case. Have a look at this fiddlealso.

对于你的情况。也看看这个小提琴

回答by Musa

Old way (if you don't now the length of arguments/parameters)

旧方法(如果您现在不知道参数/参数的长度)

 >> function sumla1(){

    result=0
    for(let i=0; i<arguments.length;i++){

        result+=arguments[i];

    }
    return result;
    }
    >> sumla1(45,67,88);
    >> 200

ES6 (destructuring of array)

ES6(数组的解构)

>> function sumla2(...x){return x.reduce((a,b)=>a+b)}
>>
>> sumla2(5,5,6,7,8)
>>
>> 31
>>
>> var numbers = [4, 9, 16, 25];
>> sumla2(...numbers);
>> 54