Javascript 使用jQuery的数组中的值的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8550183/
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-08-24 06:28:26  来源:igfitidea点击:

Sum of values in an array using jQuery

javascriptjqueryarrays

提问by Aman Virk

I have an array containing some values and I want to get their sum. Here is the example:

我有一个包含一些值的数组,我想得到它们的总和。这是示例:

var somearray = ["20","40","80","400"];

I want to sum these values using jQuery. In this example the result would be 540.

我想使用 jQuery 对这些值求和。在这个例子中,结果是 540。

回答by vol7ron

To also handle floating point numbers:

还要处理浮点数:

  • (Older) JavaScript:

    var arr = ["20.0","40.1","80.2","400.3"],
        n   = arr.length,
        sum = 0;
    while(n--)
       sum += parseFloat(arr[n]) || 0;
    
  • ECMA 5.1/6:

    var arr = ["20.0","40.1","80.2","400.3"],
        sum = 0;
    arr.forEach(function(num){sum+=parseFloat(num) || 0;});
    
  • ES6:

    var sum = ["20.0","40.1","80.2","400.3"].reduce((pv,cv)=>{
       return pv + (parseFloat(cv)||0);
    },0);
    

    The reduce() is available in older ECMAScript versions, the arrow function is what makes this ES6-specific.

    I'm passing in 0 as the first pvvalue, so I don't need parseFloataround it — it'll always hold the previous sum, which will always be numeric. Because the current value, cv, can be non-numeric (NaN), we use ||0on it to skip that value in the array. This is terrific if you want to break up a sentence and get the sum of the numbers in it. Here's a more detailed example:

    let num_of_fruits = `
       This is a sentence where 1.25 values are oranges 
       and 2.5 values are apples. How many fruits are 
       there?
    `.split(/\s/g).reduce((p,c)=>p+(parseFloat(c)||0), 0); 
    
    // num_of_fruits == 3.75
    

  • jQuery:

    var arr = ["20.0","40.1","80.2","400.3"],
        sum = 0;
    $.each(arr,function(){sum+=parseFloat(this) || 0;});
    
  • (旧)JavaScript:

    var arr = ["20.0","40.1","80.2","400.3"],
        n   = arr.length,
        sum = 0;
    while(n--)
       sum += parseFloat(arr[n]) || 0;
    
  • ECMA 5.1/6:

    var arr = ["20.0","40.1","80.2","400.3"],
        sum = 0;
    arr.forEach(function(num){sum+=parseFloat(num) || 0;});
    
  • ES6:

    var sum = ["20.0","40.1","80.2","400.3"].reduce((pv,cv)=>{
       return pv + (parseFloat(cv)||0);
    },0);
    

    reduce() 在较旧的 ECMAScript 版本中可用,箭头函数是使此 ES6 特定的原因。

    我传入 0 作为第一个pv值,所以我不需要parseFloat围绕它——它总是保存前一个总和,它总是数字。因为当前值 ,cv可以是非数字 ( NaN),所以我们使用||0它来跳过数组中的那个值。如果你想分解一个句子并得到其中数字的总和,这太棒了。这是一个更详细的例子:

    let num_of_fruits = `
       This is a sentence where 1.25 values are oranges 
       and 2.5 values are apples. How many fruits are 
       there?
    `.split(/\s/g).reduce((p,c)=>p+(parseFloat(c)||0), 0); 
    
    // num_of_fruits == 3.75
    

  • jQuery:

    var arr = ["20.0","40.1","80.2","400.3"],
        sum = 0;
    $.each(arr,function(){sum+=parseFloat(this) || 0;});
    


What the above gets you:

以上内容为您提供:

  • ability to input any kind of value into the array; number or numeric string(123or "123"), floating point string or number ("123.4"or 123.4), or even text (abc)
  • only adds the valid numbers and/or numeric strings, neglecting any bare text (eg [1,'a','2'] sums to 3)
  • 能够将任何类型的值输入到数组中;数字或数字字符串(123"123"),浮点字符串或数字("123.4"123.4),甚至文本(abc
  • 仅添加有效数字和/或数字字符串,忽略任何裸文本(例如 [1,'a','2'] 总和为 3)

回答by Mark Byers

You don't need jQuery. You can do this using a forloop:

你不需要jQuery。您可以使用for循环执行此操作:

var total = 0;
for (var i = 0; i < someArray.length; i++) {
    total += someArray[i] << 0;
}

Related:

有关的:

回答by Codler

You can use reducewhich works in all browser except IE8 and lower.

您可以reduce在除 IE8 及更低版本之外的所有浏览器中使用它。

["20","40","80","400"].reduce(function(a, b) {
    return parseInt(a, 10) + parseInt(b, 10);
})

回答by Praveen Vijayan

Another method, if eval is safe & fast :

另一种方法,如果 eval 安全且快速:

eval(["10","20","30","40","50"].join("+"))

回答by gion_13

If you want it to be a jquery method, you can do it like this :

如果你希望它是一个 jquery 方法,你可以这样做:

$.sum = function(arr) {
    var r = 0;
    $.each(arr, function(i, v) {
        r += +v;
    });
    return r;
}

and call it like this :

并这样称呼它:

var sum = $.sum(["20", "40", "80", "400"]);

回答by Sudhir Bastakoti

var total = 0;
$.each(someArray,function() {
    total += parseInt(this, 10);
});

回答by Lodewijk

In http://bugs.jquery.com/ticket/1886it becomes obvious that the jQuery devs have serious mental issues reg. functional programming inspired additions. Somehow it's good to have some fundamental things (like map) but not others (like reduce), unless it reduces jQuery's overall filesize. Go figure.

http://bugs.jquery.com/ticket/1886 中,很明显 jQuery 开发人员有严重的心理问题。函数式编程启发了添加。不知何故,拥有一些基本的东西(比如地图)而不是其他东西(比如减少)是好的,除非它减少了 jQuery 的整体文件大小。去搞清楚。

Helpfully, someone placed code to use the normal reduce function for jQuery arrays:

有用的是,有人放置了代码来使用 jQuery 数组的普通 reduce 函数:

$.fn.reduce = [].reduce;

$.fn.reduce = [].reduce;

Now we can use a simple reduce function to create a summation:

现在我们可以使用一个简单的 reduce 函数来创建一个求和:

//where X is a jQuery array
X.reduce(function(a,b){ return a + b; });
// (change "a" into parseFloat("a") if the first a is a string)

Lastly, as some older browsers hadn't yet implemented reduce, a polyfill can be taken from MDN(it's big but I guess it has the exact same behavior, which is desirable):

最后,由于一些较旧的浏览器还没有实现 reduce,可以从MDN 中获取一个 polyfill (它很大,但我猜它具有完全相同的行为,这是可取的):

if ( 'function' !== typeof Array.prototype.reduce ) {
    Array.prototype.reduce = function( callback /*, initialValue*/ ) {
        'use strict';
        if ( null === this || 'undefined' === typeof this ) {
          throw new TypeError(
             'Array.prototype.reduce called on null or undefined' );
        }
        if ( 'function' !== typeof callback ) {
          throw new TypeError( callback + ' is not a function' );
        }
        var t = Object( this ), len = t.length >>> 0, k = 0, value;
        if ( arguments.length >= 2 ) {
          value = arguments[1];
        } else {
          while ( k < len && ! k in t ) k++; 
          if ( k >= len )
            throw new TypeError('Reduce of empty array with no initial value');
          value = t[ k++ ];
        }
        for ( ; k < len ; k++ ) {
          if ( k in t ) {
             value = callback( value, t[k], k, t );
          }
        }
        return value;
      };
    }

回答by RIYAJ KHAN

You can do it in this way.

你可以这样做。

var somearray = ["20","40","80","400"];

somearray = somearray.map(Number);

var total = somearray.reduce(function(a,b){  return a+b },0)

console.log(total);

回答by Annunaki

    var arr = ["20.0","40.1","80.2","400.3"],
    sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0; });

Worked perfectly for what i needed. Thanks vol7ron

完美地满足了我的需要。谢谢 vol7ron