UPDATE - To combine Andy's method and the Prototyping method...
Array.prototype.sum = function(){
return this.reduce(function(a,b) {return a+b} );
}
Now all array will have the sum
method. eg var total = myArray.sum();
.
Original answer...
I'd be tempted with just
var myArray = [1,2,3,4,5];
var sum = 0;
for (var i=0, iMax=myArray.length; i < iMax; i++){
sum += myArray[i];
};
alert(sum);
break it out into a function if you're using it a lot. Or even neater, prototype it...
Array.prototype.sum = function(){
for(var i=0, sum=0, max=this.length; i < max; sum += this[i++]);
return sum;
}
var myArray = [1,2,3,4,5];
alert(myArray.sum());
Courtesy of DZone Snippets