Break โดยไม่มี Label
break โดยไม่มี label ใช้เพื่อออกจากลูปที่ใกล้ที่สุด (innermost loop) ทันที
ตัวอย่าง
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20) {
if (x == 5){
break; // ออกจากลูป while ทันที
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
ผลลัพธ์: แสดงตัวเลข 2,3,4,5 แล้วจบลูป (ไม่แสดง 6-20)
Break พร้อม Label
Label ใช้ควบคุมโฟลว์ของโปรแกรม เช่น ใน Nested Loop เพื่อกระโดดออกจากลูปภายนอกได้ทันที
ตัวอย่าง
<html>
<body>
<script>
document.write("Entering the loop!<br /> ");
outerloop: // Label ชื่อ outerloop
for (var i = 0; i < 5; i++) {
document.write("Outerloop: " + i + "<br />");
innerloop: // Label ชื่อ innerloop
for (var j = 0; j < 5; j++) {
if (j > 3 ) break; // ออกจาก innerloop เท่านั้น
if (i == 2) break innerloop; // ออกจาก innerloop (เหมือนข้างบน)
if (i == 4) break outerloop; // ออกจาก outerloop ทันที
document.write("Innerloop: " + j + " <br />");
}
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
ตารางเปรียบเทียบ
| คุณสมบัติ | break (ไม่มี label) | break labelName |
|---|---|---|
| ขอบเขตการออก | ลูปที่ใกล้ที่สุดเท่านั้น | ลูปที่ระบุโดย label (อาจเป็นลูปภายนอก) |
| ใช้ใน Nested Loop | ออกจากลูปในชั้นเดียว | ออกจากลูปชั้นนอกได้ทันที |
| ความยืดหยุ่น | จำกัด | สูง |
ข้อควรระวัง
- Label ต้องวางไว้ก่อนคำสั่งลูปโดยตรง
- ชื่อ Label ต้องไม่ซ้ำกับคำสงวน
- ใช้ Label เฉพาะเมื่อจำเป็นจริงๆ เพราะอาจทำให้โค้ดยากต่อการติดตาม