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
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
var arr = [1,2,3,4];
var total=0;
for(var i in arr) { total += arr[i]; }
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();
I would just loop through the elements and add them up.
However, jquery.arrayUtils.js looks interesting.