Label ช่วยให้ continue สามารถ ระบุลูปชั้นนอกที่ต้องการข้ามรอบ ได้ แทนที่จะข้ามแค่ลูปชั้นในสุด (Default Behavior)
ตัวอย่างโค้ด
<html>
<body>
<script>
document.write("Entering the loop!<br />");
outerloop: // Label Name
for (var i = 0; i < 3; i++) {
document.write("Outerloop: " + i + "<br />");
for (var j = 0; j < 5; j++) {
if (j == 3) {
continue outerloop; // ข้ามรอบ outer ที่เหลือ ไปรอบ i ถัดไป
}
document.write("Innerloop: " + j + "<br />");
}
}
document.write("Exiting the loop!<br />");
</script>
</body>
</html>
ผลลัพธ์
Entering the loop! Outerloop: 0 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 1 Innerloop: 0 Innerloop: 1 Innerloop: 2 Outerloop: 2 Innerloop: 0 Innerloop: 1 Innerloop: 2 Exiting the loop!
การวิเคราะห์ Flow
i=0: วน j=0,1,2,3 → เจอcontinue outerloop→ ข้าม j=4, ไปi=1ทันทีi=1: วน j=0,1,2,3 →continue outerloop→ ไปi=2i=2: วน j=0,1,2,3 →continue outerloop→ จบ outerloop
ผลคือ Innerloop พิมพ์แค่ 0,1,2 ทุกรอบ Outerloop
เปรียบเทียบ: ไม่มี Label vs มี Label
// ไม่มี Label: continue ทำงานกับ inner loop
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 5; j++) {
if (j === 3) continue; // ข้ามแค่ j=3, ทำ j=4 ต่อ
console.log(i, j);
}
}
// พิมพ์: (0,0)(0,1)(0,2)(0,4) (1,0)(1,1)(1,2)(1,4) (2,0)(2,1)(2,2)(2,4)
// มี Label: continue ทำงานกับ outer loop
outer: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 5; j++) {
if (j === 3) continue outer; // ข้าม j=3,4 และ i ที่เหลือในรอบนี้
console.log(i, j);
}
}
// พิมพ์: (0,0)(0,1)(0,2) (1,0)(1,1)(1,2) (2,0)(2,1)(2,2)
ข้อควรระวัง
- Label ต้องอยู่ ทันทีก่อน Statement ที่ต้องการ Label (Loop หรือ Block)
continue labelใช้ได้กับ Loop เท่านั้น (Block ไม่ได้)- Label Name ต้อง Unique ใน Function Scope
- ใช้ Label อย่างน้อยที่สุด - ทำให้ Control Flow ยากต่อการติดตาม
แนวทาง Refactor แทน Label
// แทน Label + Continue
function processGrid(grid) {
for (const row of grid) {
if (shouldSkipRow(row)) continue; // Row-level continue
for (const cell of row) {
if (shouldSkipCell(cell)) continue; // Cell-level continue
processCell(cell);
}
}
}
// หรือใช้ Functional Approach
grid
.filter(row => !shouldSkipRow(row))
.forEach(row =>
row
.filter(cell => !shouldSkipCell(cell))
.forEach(processCell)
);