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

Label Statements ใน JavaScript คืออะไร?


Label Statement ใช้ ตั้งชื่อ (Identifier) ให้กับ Statement หรือ Block เพื่อให้ break และ continue สามารถ อ้างอิงเป้าหมายได้ชัดเจน โดยเฉพาะใน Nested Loops

ไวยากรณ์

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

ตัวอย่าง 1: 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>

ตัวอย่าง 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;
        document.write("Innerloop: " + j + "<br />");
      }
    }
    document.write("Exiting the loop!<br />");
  </script>
</body>
</html>

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

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

myBlock: {
  console.log("Start");
  if (condition) break myBlock; // ออกจาก Block
  console.log("Middle");
  console.log("End");
}
console.log("After Block");

ข้อกำหนด Label Name

  • ต้องเป็น Valid Identifier (ขึ้นต้นตัวอักษร, $, _ ตามด้วยตัวอักษร/ตัวเลข/$/_)
  • ไม่ใช่ Reserved Word
  • Case-sensitive
  • Unique ใน Function Scope เดียวกัน

Scope และข้อจำกัด

  • Label Scope = Function Scope (เหมือน var)
  • ไม่สามารถ Jump ข้าม Function Boundary (ไม่ใช่ Goto)
  • break label ใช้ได้กับ Loop และ Block
  • continue label ใช้ได้กับ Loop เท่านั้น

แนวทางปฏิบัติและตัวเลือกแทน

ตัวอย่าง Refactor

// ❌ Label + Break
outer: for (const user of users) {
  for (const post of user.posts) {
    if (post.id === targetId) break outer;
  }
}

// ✅ Function + Return
function findPost(users, targetId) {
  for (const user of users) {
    for (const post of user.posts) {
      if (post.id === targetId) return post;
    }
  }
  return null;
}
สถานการณ์แนะนำ
Break Nested LoopExtract เป็น Function + Return
Continue Outer LoopGuard Clause / Extract Function
Complex State MachineState Pattern / Switch ใน While Loop
Legacy Code MaintenanceLabel OK (ถ้า Refactor ยาก)