Оператор Switch в JavaScript: объяснение синтаксиса и методов

Синтаксис оператора switchJavaScript следующий:

switch (expression) {
  case value1:
    // Code to be executed when the expression matches value1
    break;
  case value2:
    // Code to be executed when the expression matches value2
    break;
  case value3:
    // Code to be executed when the expression matches value3
    break;
  default:
    // Code to be executed when none of the cases match the expression
}

В этом синтаксисе оценивается выражение, и его значение сравнивается со значениями, указанными в операторах case. Если совпадение найдено, соответствующий блок кода выполняется. Оператор breakиспользуется для выхода из оператора switchпосле того, как найдено совпадение. Если совпадений не обнаружено, выполняется блок кода в случае default.

Вот несколько дополнительных методов, которые можно использовать с оператором switch:

  1. Несколько случаев. У вас может быть несколько операторов case, которые используют один и тот же блок кода. Например:
switch (expression) {
  case value1:
  case value2:
    // Code to be executed when the expression matches value1 or value2
    break;
  case value3:
    // Code to be executed when the expression matches value3
    break;
  default:
    // Code to be executed when none of the cases match the expression
}
  1. Поведение при провале: опуская оператор breakв конце case, вы можете добиться поведения при провале, при котором выполнение кода продолжается до следующего Блок case. Например:
switch (expression) {
  case value1:
    // Code to be executed when the expression matches value1
  case value2:
    // Code to be executed when the expression matches value1 or value2
    break;
  case value3:
    // Code to be executed when the expression matches value3
    break;
  default:
    // Code to be executed when none of the cases match the expression
}
  1. Использование выражений в случаях. Вы можете использовать выражения в операторах case. Например:
switch (true) {
  case expression1:
    // Code to be executed when expression1 evaluates to true
    break;
  case expression2:
    // Code to be executed when expression2 evaluates to true
    break;
  default:
    // Code to be executed when none of the cases match the expression
}