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

Cách thoát khỏi switch case trong JavaScript

Sử dụng break

Mỗi case nên kết thúc bằng break để thoát switch. Nếu thiếu, sẽ fall-through sang case tiếp theo.

Ví dụ

<script>
var grade = 'A';
document.write("Vao switch<br>");
switch (grade) {
  case 'A': document.write("Xuat sac<br>"); break;
  case 'B': document.write("Gioi<br>"); break;
  case 'C': document.write("Kha<br>"); break;
  case 'D': document.write("Trung binh<br>"); break;
  case 'F': document.write("Yeu<br>"); break;
  default: document.write("Diem khong hop le<br>");
}
document.write("Thoat switch");
</script>

Fall-through có chủ đích

switch (month) {
  case 12:
  case 1:
  case 2:
    season = "Mua dong";
    break;
  case 3: case 4: case 5:
    season = "Mua xuan";
    break;
  // ...
}

Lưu ý

  • So sánh dùng strict equality (===).
  • default không bắt buộc, nhưng khuyến nghị có.
  • Có thể gom nhiều case liên tiếp.
  • ES2022 proposal: switch expression (trả về giá trị) – chưa chuẩn.