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

วิธีที่ดีที่สุดในการ Break ออกจาก Nested Loops ใน JavaScript


วิธีที่ดีที่สุดในการออกจาก Nested Loops (ลูปซ้อน) คือการใช้ Label Statement ร่วมกับ 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 (Explicit)
        if (i == 4) break outerloop; // ออกจาก outerloop!
        document.write("Innerloop: " + j + " <br />");
      }
    }
    document.write("Exiting the loop!<br />");
  </script>
</body>
</html>

วิธีอื่นๆ (Alternatives)

1. Function + Return (แนะนำมากที่สุด - Cleanest)

function findInMatrix(matrix, target) {
  for (let i = 0; i < matrix.length; i++) {
    for (let j = 0; j < matrix[i].length; j++) {
      if (matrix[i][j] === target) {
        return { row: i, col: j }; // ออกจากทั้ง Function ทันที
      }
    }
  }
  return null;
}

2. Flag Variable (Traditional)

let found = false;
for (let i = 0; i < 5 && !found; i++) {
  for (let j = 0; j < 5; j++) {
    if (condition) {
      found = true;
      break; // ออก inner loop
    }
  }
}
// Outer loop condition && !found จะหยุด

3. IIFE (Immediately Invoked Function Expression)

const result = (() => {
  for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
      if (condition) return { i, j }; // Return จาก IIFE
    }
  }
  return null;
})();

4. Exception (Non-local Exit - ใช้เฉพาะ Error Cases)

try {
  for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
      if (condition) throw { i, j, type: 'Found' };
    }
  }
} catch (e) {
  if (e.type === 'Found') { /* handle */ }
  else throw e;
}

เปรียบเทียบวิธีต่างๆ

วิธีความชัดเจนPerformanceเหมาะสำหรับ
Label + BreakปานกลางดีLogic ซับซ้อนใน Loop เดียว
Function + Returnดีที่สุดดีส่วนใหญ่ (Reusable, Testable)
Flag Variableต่ำ (Verbose)ดีLegacy Code / ไม่สามารถ Return ได้
IIFEปานกลางพอใช้One-off ใน Scope เดียว
Exceptionต่ำช้าError Handling เท่านั้น

แนวทางปฏิบัติที่ดี

  • ค่า Default: ใช้ Function + Early Return
  • ถ้าอยู่ใน Function แล้ว: Return ทันที
  • ถ้าไม่สามารถ Return ได้: ใช้ Label + Break (พร้อม Comment)
  • หลีกเลี่ยง Flag Variable และ Exception สำหรับ Control Flow ปกติ
  • พิจารณา Array Methods: find, findIndex, some, every