Sum //JavaScript Repository

Description

Sum all the elements of a numeric array.
Created: 2005.11.04

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/array/sum [rev. #1]

sum = function(o){
    for(var s = 0, i = o.length; i; s += o[--i]);
    return s;
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

var x = [1, 2, 3, 4, 5, 6, 7, 8, 9];
document.write("A = ", x, "<br />sum(A) = ", sum(x));

//]]>
</script>

Help

sum(vector: Array): Number
Returns the sum of all the elements in a numeric array.
vector
array which the elements will be analyzed

Rank (Votes: 106)

2.29