這是ES6版的
const numbers = [10, 20, 30, 40] // sums to 100
// function for adding two numbers. Easy!
const add = (a, b) =>
a + b
// use reduce to sum our array
const sum = numbers.reduce(add)
也可以這樣寫
var numbers = [65, 44, 12, 4];
function getSum(total, num) {
return total + num;
}
function myFunction(item) {
document.getElementById("demo").innerHTML = numbers.reduce(getSum);
}
比較古早的ES5寫法:
var numbers = [10, 20, 30, 40] // sums to 100
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i]
}
參考文章:
Rewriting JavaScript: Sum an Array
JavaScript Array reduce() Method