while loops
while repeats
while (test) { ... }runs again and again, as long as the test staystrue.- It checks the test before each pass — so the body might run zero times.
while ทำซ้ำ
while (test) { ... }รันซ้ำแล้วซ้ำเล่า ตราบใดที่ เงื่อนไขยังคงtrue- มันตรวจสอบเงื่อนไข ก่อน การวนรอบแต่ละครั้ง - ดังนั้น Body อาจรันศูนย์ครั้ง
let n = 1;
while (n <= 3) {
console.log(n); // → 1, then 2, then 3
n++;
}
Make progress every pass
- Something inside must move the test toward
false. - If nothing changes, the loop never stops — an infinite loop (the Stop button saves you).
สร้างความก้าวหน้าทุกรอบ
- ต้องมีบางสิ่งภายในที่ทำให้เงื่อนไขเข้าใกล้
false - หากไม่มีอะไรเปลี่ยน Loop จะไม่หยุดเลย - Infinite loop (ปุ่ม Stop ช่วยคุณได้)
let n = 1;
while (n < 50) {
n = n * 2; // 2, 4, 8, 16, 32, 64 — then stop
}
console.log(n); // → 64
Each pass doubles n · แต่ละรอบทำให้ n คู่เท่าตัว
while re-checks its test each pass. n must change, or it runs forever. · while ตรวจสอบ test ของมันอีกครั้งในแต่ละรอบ. n ต้องเปลี่ยน, หรือมันจะรันตลอดไป
Common mistakes
- Change the condition inside the loop, or it runs forever.
- A
whilechecks its condition first, so it may run zero times.
ข้อผิดพลาดที่พบบ่อย
- เปลี่ยนเงื่อนไขภายใน Loop มิฉะนั้นมันจะรันตลอดกาล
- A
whileตรวจสอบเงื่อนไขก่อน ดังนั้นอาจรันศูนย์ครั้ง
Now you try
- Use a
whileloop. - Press Check answer to test it.
ลองดูเลย
- ใช้Loop
while - กด Check answer เพื่อทดสอบ
let n = 3. Use a while loop to count down: log 3, 2, 1, one per line. · let n = 3. ใช้ลูป while เพื่อนับ ลง: log 3, 2, 1, อย่างละบรรทัด
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
let n = 1. While n is 16 or less, log n then double it. Output should be 1, 2, 4, 8, 16. · let n = 1. จนกว่า n จะมีค่าน้อยกว่าหรือเท่ากับ 16 ให้แสดง n แล้วคูณสอง ผลลัพธ์ที่ควรแสดงคือ 1, 2, 4, 8, 16
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Use a while loop to add up 1 to 4, then log the total (it is 10). · ใช้ลูป while เพื่อบวกเลขตั้งแต่ 1 ถึง 4 แล้วแสดงผลรวม (ค่าที่ได้คือ 10)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่