Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)
I thought $.each might be useful,
This is possible by looping over all items, and adding them on each iteration to a sum-variable.
var array = [1, 2, 3];
for (var i = 0, sum = 0; i < array.length; sum += array[i++]);
JavaScript doesn't know block scoping, so sum will be accesible:
console.log(sum); // => 6
The same as above, however annotated and prepared as a simple function:
function sumArray(array) {
for (
var
index = 0, // The iterator
length = array.length, // Cache the array length
sum = 0; // The total amount
index < length; // The "for"-loop condition
sum += array[index++] // Add number on each iteration
);
return sum;
}