บทความนี้รวมคำอธิบาย 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 Loop | Loop, Switch, Label |
continue | ข้ามรอบนี้ ไปรอบถัดไป | Innermost Loop | Loop, Label |
label: | ตั้งชื่อ Target | Function Scope | Loop, Block (break only) |
break label | ออกจาก Loop/Block ที่ Label | Specified Label | Loop, Block |
continue label | ข้ามรอบ Loop ที่ Label | Specified Label | Loop เท่านั้น |
แนวทางปฏิบัติสมัยใหม่ (Modern Alternatives)
- ใช้ Function + Early Return แทน Break/Label ใน Function
- ใช้ Array Methods (
find,some,every,filter) แทน Loop + Break/Continue - ใช้ for...of ร่วมกับ
break/continue(รองรับ Label ได้) - หลีกเลี่ยง Label ในโค้ดใหม่ - Refactor ให้ชัดเจนกว่า