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

Common Code Blocks (Khối mã chung) trong Switch JavaScript

Trong switch, nhiều case có thể chia sẻ cùng một khối code bằng cách **bỏ break** giữa các case liên tiếp. Kỹ thuật này gọi là fall-through.

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Switch Common Code Blocks</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
    .result { font-size: 20px; font-weight: 500; margin: 10px 0; color: green; }
    input { padding: 8px; font-size: 16px; width: 60px; }
    button { padding: 8px 16px; cursor: pointer; font-size: 16px; }
  </style>
</head>
<body>
  <h1>Switch Statement - Common Code Blocks</h1>
  Nhập ngày 1-7: <input type="text" class="day" id="dayInput" />
  <button class="Btn" id="btn">CHECK</button>
  <div class="result" id="result"></div>
  <h3> Nhấn CHECK để xem ngày trong tuần (nhóm weekday/weekend) </h3>
  <script>
    const dayVal = document.querySelector("#dayInput");
    const resEle = document.querySelector("#result");
    
    document.querySelector("#btn").addEventListener("click", () => {
      const day = parseInt(dayVal.value); // Ép kiểu số
      switch (day) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          resEle.innerHTML = "Ngày làm việc (Weekday)";
          break;
        case 6:
        case 7:
          resEle.innerHTML = "Cuối tuần (Weekend)";
          break;
        default:
          resEle.innerHTML = "Nhập giá trị 1-7";
          break;
      }
    });
  </script>
</body>
</html>

Kết quả

  • Nhập 1-5 → Ngày làm việc (Weekday)
  • Nhập 6-7 → Cuối tuần (Weekend)
  • Nhập khác → Nhập giá trị 1-7

Cơ chế Fall-through:

switch (value) {
  case 1:
  case 2:
    // Chạy cho cả 1 và 2
    console.log("1 hoặc 2");
    break; // Quan trọng! Nếu thiếu, sẽ chạy tiếp case 3
  case 3:
    console.log("3");
    break;
}

⚠️ Cảnh báo: Fall-through vô ý

// LỖI HAY GẶP: quên break
switch (x) {
  case 1:
    console.log("One");
    // Thiếu break!
  case 2:
    console.log("Two"); // Chạy cả khi x=1
}

ESLint rule no-fallthrough cảnh báo lỗi này. Nếu **ý định** fall-through, thêm comment:

switch (x) {
  case 1:
    doSomething();
    // falls through
  case 2:
    doSomethingElse();
    break;
}

Pattern hiện đại thay thế (Object/Map):

// Nhóm weekday/weekend
const dayType = {
  1: "Weekday", 2: "Weekday", 3: "Weekday",
  4: "Weekday", 5: "Weekday",
  6: "Weekend", 7: "Weekend"
};
const result = dayType[day] || "Invalid";

// Hoặc dùng Set cho nhóm
const weekdays = new Set([1,2,3,4,5]);
const weekends = new Set([6,7]);
if (weekdays.has(day)) ...
if (weekends.has(day)) ...

Khi nào dùng switch?

  • So sánh một giá trị với nhiều hằng số
  • Cần fall-through ý định
  • Code dễ đọc hơn if-else chuỗi dài
  • Enum-like values

Khi nào KHÔNG nên dùng switch?

  • Điều kiện phức tạp (range, logic boolean)
  • So sánh object/reference
  • Chỉ 2-3 trường hợp (if-else gọn hơn)