Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách tốt nhất thoát nested loops trong JavaScript

Giải pháp: Label + break

Gán label cho outer loop, dùng break label từ inner loop.

Ví dụ

<script>
document.write("Vao vong lap<br>");
outer: for (var i = 0; i < 5; i++) {
  document.write("Outer: " + i + "<br>");
  inner: for (var j = 0; j < 5; j++) {
    if (j > 3) break;        // thoát inner
    if (i == 2) break inner; // thoát inner (explicit)
    if (i == 4) break outer; // thoát outer
    document.write("  Inner: " + j + "<br>");
  }
}
document.write("Thoat!<br>");
</script>

Các cách khác

Phương phápƯu điểmNhược điểm
Label + breakRõ ràng, chuẩn JSÍt quen, label dễ quên
Biến flagDễ hiểuVerbose, dễ bug quên reset
Tách function + returnClean, reusable, testableCần đóng gói logic
try/catch + throwThoát sâu nhiều cấpDùng exception cho control flow (anti-pattern)
Array.some/everyFunctional, ngắnChỉ boolean, không trả giá trị tìm thấy

Khuyến nghị tốt nhất

Tách thành hàm riêng + return sớm – code rõ ràng, dễ test, không cần label.

function findMatch(matrix, target) {
  for (const row of matrix) {
    for (const cell of row) {
      if (cell === target) return cell; // thoát ngay 2 vòng
    }
  }
  return null;
}