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

การใช้ Label ควบคุม Flow ใน JavaScript


Label Statement ใช้ ตั้งชื่อให้ Statement หรือ Block เพื่อให้ break และ continue สามารถ ระบุเป้าหมายลูปที่ต้องการควบคุม ได้อย่างแม่นยำ (โดยเฉพาะ Nested Loops)

ไวยากรณ์

labelName: statement
// หรือ
labelName: { block }

ตัวอย่าง 1: Label กับ break (ออกจากลูปชั้นนอก)

<html>
<body>
  <script>
    document.write("Entering the loop!<br />");
    outerloop: // Label Name
    for (var i = 0; i < 5; i++) {
      document.write("Outerloop: " + i + "<br />");
      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>

ตัวอย่าง 2: 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; // ข้ามรอบ outer ที่เหลือ ไปรอบ i ถัดไป
        }
        document.write("Innerloop: " + j + "<br />");
      }
    }
    document.write("Exiting the loop!<br />");
  </script>
</body>
</html>

ผลลัพธ์ตัวอย่าง 2

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!

สังเกต: เมื่อ j=3 จะ continue outerloop ทำให้ innerloop หยุด พิมพ์ Outerloop ถัดไปทันที

Label กับ Block Statement (ไม่ใช่ Loop)

Label สามารถใช้กับ Block { } ได้ แต่ break เท่านั้น (continue ไม่ได้):

myBlock: {
  console.log("Start");
  if (condition) break myBlock; // ออกจาก Block
  console.log("End"); // ไม่รันถ้า break
}
console.log("After Block");

ข้อจำกัดและแนวทางปฏิบัติ

  • Label Name ต้องเป็น Identifier ที่ถูกต้อง (ไม่ใช่ Reserved Word)
  • Label Scope: Function Scope (เหมือน var)
  • ไม่สามารถ กระโดดข้าม Function Boundary (ไม่ใช่ Goto)
  • ใช้ เฉพาะเมื่อจำเป็น (Nested Loops ซับซ้อน) โค้ดจะอ่านยาก
  • ตัวเลือกที่ดีกว่า: Refactor เป็น Function + Return, ใช้ Array Methods, หรือ Flag Variable

ตัวเลือกแทน Label (Modern Approach)

// แทน Label + Break
function findMatch(matrix, target) {
  for (const row of matrix) {
    for (const cell of row) {
      if (cell === target) return cell; // Early Return
    }
  }
  return null;
}

// แทน Label + Continue
function processMatrix(matrix) {
  for (const row of matrix) {
    if (shouldSkipRow(row)) continue; // Row-level continue
    for (const cell of row) {
      if (shouldSkipCell(cell)) continue; // Cell-level continue
      process(cell);
    }
  }
}