Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

คำสั่ง do...while loop ใน JavaScript คืออะไร?


คำสั่ง do...while เป็นลูปที่ ตรวจสอบเงื่อนไขหลังรันบล็อกโค้ด (Post-test Loop) ทำให้ รันอย่างน้อย 1 รอบ เสมอ แม้เงื่อนไขจะเป็น false ตั้งแต่แรก

ไวยากรณ์

do {
  // โค้ดที่จะรัน (อย่างน้อย 1 ครั้ง)
} while (condition); // ต้องมี Semicolon ท้าย

ตัวอย่างโค้ด

<html>
<body>
  <script>
    var count = 0;
    document.write("Starting Loop<br />");
    do {
      document.write("Current Count: " + count + "<br/>");
      count++;
    } while (count < 5);
    document.write("Loop stopped!");
  </script>
</body>
</html>

ผลลัพธ์

Starting Loop
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Loop stopped!

เปรียบเทียบ while vs do...while

ลักษณะwhiledo...while
ตรวจสอบเงื่อนไขก่อนรัน (Pre-test)หลังรัน (Post-test)
รันขั้นต่ำ0 ครั้ง1 ครั้ง
Semicolon ท้ายไม่ต้องต้องมี (;)
ใช้เมื่ออาจไม่ต้องรันเลยต้องรันอย่างน้อย 1 ครั้ง

ตัวอย่างที่ do...while เหมาะสม

1. Menu/Input Validation (ต้องแสดงเมนู/ขอ Input อย่างน้อย 1 ครั้ง)

let input;
do {
  input = prompt("Enter a number (0 to exit):");
  if (input !== null) {
    const num = Number(input);
    if (!isNaN(num)) {
      console.log("You entered:", num);
    }
  }
} while (input !== "0" && input !== null);

2. Game Loop (ต้องรัน Frame แรก)

do {
  updateGameState();
  render();
} while (!gameOver);

3. Retry Logic

let attempts = 0;
let success = false;
do {
  try {
    await riskyOperation();
    success = true;
  } catch (e) {
    attempts++;
    await delay(1000);
  }
} while (!success && attempts < 3);

ข้อควรระวัง

  • ลืม ; ท้าย while(...); → Syntax Error
  • Infinite Loop: เงื่อนไขไม่เป็น false เลย (ต้องมี Logic เปลี่ยนเงื่อนไขในบล็อก)
  • ตัวแปรในเงื่อนไขต้องประกาศนอกลูปหรือในบล็อก (Block Scope ด้วย let)

แปลงระหว่าง while และ do...while

// while → do...while
while (cond) { body }
// เทียบเท่า
if (cond) {
  do { body } while (cond);
}

// do...while → while
do { body } while (cond);
// เทียบเท่า
body;
while (cond) { body }