views:

302

answers:

5

I was wondering how is it possible to go through the values of an array and add their values together.

var arr = [1,2,3,4];

should I use

var add = $.each(arr,function() {


});

but how can I add the values together.

thanks

+4  A: 
var total = 0;
$.each(arr,function() {
    total += this;
});
Chacha102
Thanks Chris ... just copied and pasted from OP
Chacha102
Is there a particular reason to use each()/parseInt for this? Judging from the example given in the OP, at least, it doesn't seem like parseInt would be necessary.
Amber
I'll take it out then.
Chacha102
Thanks, it works fine.
amir
A: 
var arr = [1,2,3,4];
var total=0;
for(var i in arr) { total += arr[i]; }
Amber
+1  A: 

Depending on how often you're going to need this, you might be better to create your own function to do it.

Iterating through large arrays using the jQuery $.each method might be expensive, performance-wise. You might be better to try:

Array.prototype.Sum = function() {
  return (! this.length) ? 0 : this.slice(1).sum() +
      ((typeof this[0] == 'number') ? this[0] : 0);
};

And then you can call

var mySum = arr.Sum();
Phil.Wheeler
I would recommend Not adding the custom method directly to the Array objects' prototype. This could cause conflicts and headaches later on. Instead create your own custom method, and create it within your own namespace for your library of methods. This way you'll avoid the future conflicts that can easily happen and be hard to debug when using global functions or extending the JavaScript Object Types directly.
Chris Pietschmann
Also, the recursive approach works only for small array sizes. For large arrays, the performance can be bad. Array#slice is expensive and so is the O(n^2) memory overhead. Iterative approach is best for this.
Chetan Sastry
A: 

I would just loop through the elements and add them up.

However, jquery.arrayUtils.js looks interesting.

Sinan Ünür
A: 
var arr=[1,2,3,4];
alert(eval(arr.join('+')));
kennebec