do...while loops execute บล็อกโค้ด 1 ครั้ง แล้วทำต่อไปเรื่อยๆ ถ้า condition evaluate เป็น true while และ do...while ใช้เมื่อต้องการรันโค้ดซ้ำจน condition เป็น false
JavaScript While Loops
while loop รันบล็อกโค้ดพร้อม condition เป็น true หยุดเมื่อ condition เป็น false ใช้เมื่อไม่รู้ล่วงหน้าว่าจะรันกี่รอบ (ต่างจาก for loop ที่รู้จำนวนรอบ)
Syntax:
while (condition_is_true) {
// Run code
}
ระวัง infinite loop: condition ต้องสามารถเป็น false ได้ ไม่งั้น loop ไม่หยุด
ตัวอย่าง While Loop: นับที่นั่งว่างในงานปาร์ตี้
จำกัด 40 คน มีอยู่ 35 คน ทุกครั้งเชิคเพิ่ม 1 คน คำนวณที่นั่งว่าง:
var limit = 40;
var current_attendees = 35;
while (current_attendees < limit) {
current_attendees = current_attendees + 1;
var spaces_left = limit - current_attendees;
console.log(`There are ${spaces_left} spaces left in the party.`);
}
Output:
There are 4 spaces left in the party. There are 3 spaces left in the party. There are 2 spaces left in the party. There are 1 spaces left in the party. There are 0 spaces left in the party.
Loop รันจน current_attendees = 40 แล้วหยุด
ตัวอย่างเพิ่มเติม: วนลูป Array VIPs
var vips = ['Robert De Niro', 'Will Smith', 'Brad Pitt', 'Denzel Washington'];
var counter = 0;
while (counter < vips.length) {
console.log(vips[counter]);
counter = counter + 1;
}
Output: Robert De Niro, Will Smith, Brad Pitt, Denzel Washington
JavaScript Do-While Loops
do...while execute บล็อก 1 ครั้งก่อน แล้วเช็ค condition ถ้า true รันต่อ false หยุด
ต่าง while loop: do...while รันอย่างน้อย 1 ครั้ง แม้ condition จะ false ตั้งแต่แรก while loop ต้อง condition true ก่อนถึงรัน
Syntax:
do {
// Run code
} while (condition_is_true);
ตัวอย่าง Do-While: Guessing Game
เดาตัวเลข 1-10 จนกว่าจะถูก:
var number_to_guess = 7;
var guessed_number = 0;
do {
var input = prompt("Enter a number between 1 and 10.");
guessed_number = parseInt(input);
} while (guessed_number != number_to_guess);
prompt แสดงก่อนเช็ค condition เสมอ รันจนเดาถูก
สรุป
while loop รันซ้ำจน condition false do...while รันอย่างน้อย 1 ครั้ง แล้วเช็ค condition ใช้เมื่อต้องการรันโค้ดซ้ำจน condition เปลี่ยนเป็น false