ประกาศตัวแปร total = 0 แล้ววนลูปบวกค่าทุกตัวในอาเรย์
ตัวอย่างโค้ด
var listOfValues = [10, 3, 4, 90, 34, 56, 23, 100, 200];
var total = 0;
for (let index = 0; index < listOfValues.length; index++) {
total = total + listOfValues[index];
}
console.log("Total Values=" + total);
วิธีรันโปรแกรม
ใช้คำสั่ง node fileName.js (เช่น node demo86.js)
ผลลัพธ์
Total Values=520