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

คำสั่ง Break Continue Label ใน JavaScript


บทความนี้รวมคำอธิบาย break, continue, และ label ไว้ด้วยกัน เพื่อดูภาพรวมการควบคุม Flow ใน Loop

1. Break Statement

ออกจากลูปหรือ Switch ทันที

<html>
<body>
  <script>
    var x = 1;
    document.write("Entering the loop<br />");
    while (x < 20) {
      if (x == 5) break; // ออกจากลูป
      x = x + 1;
      document.write(x + "<br />");
    }
    document.write("Exiting the loop!<br />");
  </script>
</body>
</html>

2. Continue Statement

ข้ามรอบปัจจุบัน ไปรอบถัดไป

<html>
<body>
  <script>
    var x = 1;
    document.write("Entering the loop<br />");
    while (x < 10) {
      x = x + 1;
      if (x == 8) continue; // ข้าม 8
      document.write(x + "<br />");
    }
    document.write("Exiting the loop!<br />");
  </script>
</body>
</html>

3. Label Statement

ตั้งชื่อให้ Loop/Block เพื่อให้ break/continue ระบุเป้าหมายได้

Label + Break

<html>
<body>
  <script>
    document.write("Entering the loop!<br />");
    outerloop:
    for (var i = 0; i < 5; i++) {
      document.write("Outerloop: " + i + "<br />");
      innerloop:
      for (var j = 0; j < 5; j++) {
        if (j > 3) break;
        if (i == 2) break innerloop;
        if (i == 4) break outerloop;
        document.write("Innerloop: " + j + " <br />");
      }
    }
    document.write("Exiting the loop!<br />");
  </script>
</body>
</html>

Label + Continue

<html>
<body>
  <script>
    document.write("Entering the loop!<br />");
    outerloop:
    for (var i = 0; i < 3; i++) {
      document.write("Outerloop: " + i + "<br />");
      for (var j = 0; j < 5; j++) {
        if (j == 3) continue outerloop;
        document.write("Innerloop: " + j + "<br />");
      }
    }
    document.write("Exiting the loop!<br />");
  </script>
</body>
</html>

สรุปตารางเปรียบเทียบ

คำสั่งผลลัพธ์Scopeใช้กับ
breakออกจาก Loop/Switch ทันทีInnermost LoopLoop, Switch, Label
continueข้ามรอบนี้ ไปรอบถัดไปInnermost LoopLoop, Label
label:ตั้งชื่อ TargetFunction ScopeLoop, Block (break only)
break labelออกจาก Loop/Block ที่ LabelSpecified LabelLoop, Block
continue labelข้ามรอบ Loop ที่ LabelSpecified LabelLoop เท่านั้น

แนวทางปฏิบัติสมัยใหม่ (Modern Alternatives)

  • ใช้ Function + Early Return แทน Break/Label ใน Function
  • ใช้ Array Methods (find, some, every, filter) แทน Loop + Break/Continue
  • ใช้ for...of ร่วมกับ break/continue (รองรับ Label ได้)
  • หลีกเลี่ยง Label ในโค้ดใหม่ - Refactor ให้ชัดเจนกว่า