Khởi tạo biến total = 0, duyệt mảng và cộng dồn từng phần tử.
Ví dụ
var listOfValues = [10, 3, 4, 90, 34, 56, 23, 100, 200];
var total = 0;
for (let i = 0; i < listOfValues.length; i++) {
total += listOfValues[i];
}
console.log("Tổng: " + total);
Cách chạy
node demo.js
Kết quả
Tổng: 520
Cách hiện đại:
// reduce()
const total = listOfValues.reduce((sum, val) => sum + val, 0);
// for...of
let total = 0;
for (const val of listOfValues) total += val;