for loops
Repeating with a for loop
- A loop runs the same block many times, so you don't repeat yourself.
for (let i = 1; i <= 5; i++) { ... }has three parts: starti = 1, testi <= 5, stepi++.
ทำซ้ำด้วย for loop
- Loop รันบล็อคเดียวกันหลายครั้ง เพื่อไม่ให้ต้องทำซ้ำเอง
for (let i = 1; i <= 5; i++) { ... }มีสามส่วน: เริ่มต้นi = 1, เงื่อนไขi <= 5, ขั้นตอนi++
for (let i = 1; i <= 3; i++) {
console.log(i); // → 1, then 2, then 3
}
Build a running total
- Keep a variable outside the loop and add to it on every pass.
สร้างผลรวมสะสม
- เก็บตัวแปรไว้ภายนอก Loop และบวกเข้าไปทุกครั้งที่วนรอบ
let total = 0;
for (let i = 1; i <= 10; i++) {
total = total + i;
}
console.log(total); // → 55
Trace the running total · ติดตามผลรวม
A loop repeats its body. Step through the passes and watch total grow. · ลูปทำซ้ำ body ของมัน. เดินผ่านรอบการทำงานและดู total เติบโต
Watch out
i <= 5stops after 5;i < 5stops before 5. Picking the wrong one is the classic "off-by-one" bug.- Start the total at
0before the loop, not inside it.
ระวัง
i <= 5หยุด หลัง 5;i < 5หยุด ก่อน 5 การเลือกผิดคือ Bug แบบ "Off-by-one" คลาสสิก- ตั้งค่าผลรวมเริ่มต้นที่
0ก่อน Loop, ไม่ใช่ภายใน
Common mistakes
for (let i = 0; i < n; i++)runsntimes.- Declare the counter with
let, not without.
ข้อผิดพลาดที่พบบ่อย
for (let i = 0; i < n; i++)รันnรอบ- ประกาศตัวนับด้วย
let, ไม่ใช่โดยไม่ประกาศ
Now you try
- Use a
forloop. - Press Check answer to test it.
ลองดูเลย
- ใช้Loop
for - กด Check answer เพื่อทดสอบ
Use a for loop to log the numbers 1 to 5, one per line. · ใช้ลูป for เพื่อ log เลข 1 ถึง 5, อย่างละบรรทัด
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a for loop to add up 1 to 10, then log the total (it is 55). · ใช้ลูป for เพื่อบวกเลขตั้งแต่ 1 ถึง 10 แล้วแสดงผลรวม (ค่าที่ได้คือ 55)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a for loop to log the even numbers 2, 4, 6, one per line (step by 2 with i += 2). · ใช้ลูป for เพื่อแสดงเลขคู่ 2, 4, 6 โดยแต่ละบรรทัดหนึ่งตัว (เพิ่มทีละ 2 ด้วย i += 2)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่