- JavaScript Switch Statement
- The JavaScript Switch Statement
- Syntax
- Example
- The break Keyword
- The default Keyword
- Example
- Example
- Common Code Blocks
- Example
- Switching Details
- Strict Comparison
- Example
- switch
- Синтаксис
- Описание
- Примеры
- Пример: Использование switch
- Пример: Что случится, если не использовать break?
- Цепочки case
- Одна операция
- Цепочка операций
- Спецификации
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- The «switch» statement
- The syntax
- An example
- Grouping of “case”
- Type matters
- Tasks
- Rewrite the «switch» into an «if»
- switch case в JavaScript
- Синтаксис switch
- Пример №1
- Пример №2
- Пример №3
- Группировка case
- Пример №4
- Проверка равенства в switch
- Пример №5
- Итого
JavaScript Switch Statement
The switch statement is used to perform different actions based on different conditions.
The JavaScript Switch Statement
Use the switch statement to select one of many code blocks to be executed.
Syntax
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- If there is no match, the default code block is executed.
Example
The getDay() method returns the weekday as a number between 0 and 6.
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) <
case 0:
day = «Sunday»;
break;
case 1:
day = «Monday»;
break;
case 2:
day = «Tuesday»;
break;
case 3:
day = «Wednesday»;
break;
case 4:
day = «Thursday»;
break;
case 5:
day = «Friday»;
break;
case 6:
day = «Saturday»;
>
The result of day will be:
The break Keyword
When JavaScript reaches a break keyword, it breaks out of the switch block.
This will stop the execution inside the switch block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
Note: If you omit the break statement, the next case will be executed even if the evaluation does not match the case.
The default Keyword
The default keyword specifies the code to run if there is no case match:
Example
The getDay() method returns the weekday as a number between 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
switch (new Date().getDay()) <
case 6:
text = «Today is Saturday»;
break;
case 0:
text = «Today is Sunday»;
break;
default:
text = «Looking forward to the Weekend»;
>
The result of text will be:
The default case does not have to be the last case in a switch block:
Example
switch (new Date().getDay()) <
default:
text = «Looking forward to the Weekend»;
break;
case 6:
text = «Today is Saturday»;
break;
case 0:
text = «Today is Sunday»;
>
If default is not the last case in the switch block, remember to end the default case with a break.
Common Code Blocks
Sometimes you will want different switch cases to use the same code.
In this example case 4 and 5 share the same code block, and 0 and 6 share another code block:
Example
switch (new Date().getDay()) <
case 4:
case 5:
text = «Soon it is Weekend»;
break;
case 0:
case 6:
text = «It is Weekend»;
break;
default:
text = «Looking forward to the Weekend»;
>
Switching Details
If multiple cases matches a case value, the first case is selected.
If no matching cases are found, the program continues to the default label.
If no default label is found, the program continues to the statement(s) after the switch.
Strict Comparison
Switch cases use strict comparison (===).
The values must be of the same type to match.
A strict comparison can only be true if the operands are of the same type.
In this example there will be no match for x:
Example
let x = «0»;
switch (x) case 0:
text = «Off»;
break;
case 1:
text = «On»;
break;
default:
text = «No value found»;
>
switch
Инструкция switch сравнивает выражение со случаями, перечисленными внутри неё, а затем выполняет соответствующие инструкции.
Синтаксис
Выражение, значение которого сравнивается со всеми случаями.
Случай, который проверяется на соответствие выражению ( expression ).
Инструкции, которые выполняются, если expression соответствуют случаю.
Инструкции, выполняемые если expression не соответствует ни одному случаю.
Описание
Если выражение соответствует какому-то случаю, то выполняются инструкции этого случая. Если несколько случаев соответствуют значению, только первый случай будет использован.
Сначала программа пытается найти подходящий случай, значение которого равно значению искомого выражения (используется строгое сравнение (en-US) , ===) и затем выполняет инструкции, соответствующие случаю. Если подходящего случая нет, ищется случай по умолчанию ( default ), который не является обязательным. Если случая по умолчанию нет, выполнение продолжается на инструкции, следующей сразу после switch . По соглашению, случай default описывается последним, но это не является строгим правилом.
Опциональная инструкция break выполняет выход из блока switch . Она может располагаться в каждом из случаев, но не является обязательной. Если её нет, то выполняется следующая инструкция из блока switch .
Примеры
Пример: Использование switch
В этом примере, если expr равно «Bananas», программа находит случай «Bananas» и выполняет соответствующие инструкции. При выполнении инструкции break , выполнение продолжится за пределами switch . Если бы break не было, то выполнились бы инструкции случая «Cherries».
switch (expr) case "Oranges": console.log("Oranges are $0.59 a pound."); break; case "Apples": console.log("Apples are $0.32 a pound."); break; case "Bananas": console.log("Bananas are $0.48 a pound."); break; case "Cherries": console.log("Cherries are $3.00 a pound."); break; case "Mangoes": case "Papayas": console.log("Mangoes and papayas are $2.79 a pound."); break; default: console.log("Sorry, we are out of " + expr + "."); > console.log("Is there anything else you'd like?");
Пример: Что случится, если не использовать break?
Если вы не использовали инструкцию break , то будут выполнены инструкции следующего случая. И проверка на соответствие выражению не будет выполняться.
var foo = 0; switch (foo) case -1: console.log('negative 1'); break; case 0: // foo равно 0, случай соответствует выражению и эти инструкции будут выполнены console.log(0) // ПРИМЕЧАНИЕ: здесь могла находиться забытая инструкция break case 1: // В случае 'case 0:' не было break, инструкции данного случая также будут выполнены console.log(1); break; // В конце расположен break, поэтому выполнение не перейдёт к случаю 'case 2:' case 2: console.log(2); break; default: console.log('default'); >
Цепочки case
Одна операция
Этот метод использует тот факт, что после case нет прерывания и продолжится выполнение следующего case независимо от того, соответствует ли case предоставленному условию. Подробнее в примере «Что случится, если не использовать break?.
Это пример case с одной операцией, где четыре разных значения отрабатывают одинаково.
var Animal = 'Giraffe'; switch (Animal) case 'Cow': case 'Giraffe': case 'Dog': case 'Pig': console.log('This animal is not extinct.'); break; case 'Dinosaur': default: console.log('This animal is extinct.'); >
Цепочка операций
Это пример множественных операций внутри case , где в зависимости от предоставленного числа можно увидеть разный вывод. Здесь показывается, что операции отрабатывают в том порядке, в котором расположены case . При этом числовая последовательность может не соблюдаться. Также возможно примешать в case строки.
var foo = 1; var output = 'Output: '; switch (foo) case 0: output += 'So '; case 1: output += 'What '; output += 'Is '; case 2: output += 'Your '; case 3: output += 'Name'; case 4: output += '?'; console.log(output); break; case 5: output += '!'; console.log(output); break; default: console.log('Please pick a number from 0 to 5!'); >
Значение | Лог |
---|---|
foo is NaN or not 1 , 2 , 3 , 4 , 5 , or 0 | Please pick a number from 0 to 5! |
0 | Output: So What Is Your Name? |
1 | Output: What Is Your Name? |
2 | Output: Your Name? |
3 | Output: Name? |
4 | Output: ? |
5 | Output: ! |
Спецификации
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 17 июл. 2023 г. by MDN contributors.
Your blueprint for a better internet.
The «switch» statement
It gives a more descriptive way to compare a value with multiple variants.
The syntax
The switch has one or more case blocks and an optional default.
- The value of x is checked for a strict equality to the value from the first case (that is, value1 ) then to the second ( value2 ) and so on.
- If the equality is found, switch starts to execute the code starting from the corresponding case , until the nearest break (or until the end of switch ).
- If no case is matched then the default code is executed (if it exists).
An example
An example of switch (the executed code is highlighted):
Here the switch starts to compare a from the first case variant that is 3 . The match fails.
Then 4 . That’s a match, so the execution starts from case 4 until the nearest break .
If there is no break then the execution continues with the next case without any checks.
In the example above we’ll see sequential execution of three alert s:
alert( 'Exactly!' ); alert( 'Too big' ); alert( "I don't know such values" );
Both switch and case allow arbitrary expressions.
let a = "1"; let b = 0; switch (+a)
Here +a gives 1 , that’s compared with b + 1 in case , and the corresponding code is executed.
Grouping of “case”
Several variants of case which share the same code can be grouped.
For example, if we want the same code to run for case 3 and case 5 :
Now both 3 and 5 show the same message.
The ability to “group” cases is a side effect of how switch/case works without break . Here the execution of case 3 starts from the line (*) and goes through case 5 , because there’s no break .
Type matters
Let’s emphasize that the equality check is always strict. The values must be of the same type to match.
For example, let’s consider the code:
let arg = prompt("Enter a value?"); switch (arg)
- For 0 , 1 , the first alert runs.
- For 2 the second alert runs.
- But for 3 , the result of the prompt is a string «3» , which is not strictly equal === to the number 3 . So we’ve got a dead code in case 3 ! The default variant will execute.
Tasks
Rewrite the «switch» into an «if»
Write the code using if..else which would correspond to the following switch :
To precisely match the functionality of switch , the if must use a strict comparison ‘===’ .
For given strings though, a simple ‘==’ works too.
if(browser == 'Edge') < alert("You've got the Edge!"); >else if (browser == 'Chrome' || browser == 'Firefox' || browser == 'Safari' || browser == 'Opera') < alert( 'Okay we support these browsers too' ); >else
Please note: the construct browser == ‘Chrome’ || browser == ‘Firefox’ … is split into multiple lines for better readability.
But the switch construct is still cleaner and more descriptive.
switch case в JavaScript
switch — это конструкция, которая позволяет выполнять инструкции исходя из значения выражений. switch является более наглядным способом сравнить выражение с несколькими вариантами описанными внутри, таким образом заменяя сразу же несколько if .
Синтаксис switch
выражение — значение, которое сравнивается с value1 , value2 , value3 и т.д.
инструкция — код который выполнится, если выражение соответствует valueN .
break — команда отвечающая на выход из конструкции switch .
default — необязательный блок, который выполняется, если выражение не соответствует ни одному valueN .
Конструкция switch может иметь один или более блоков case .
Пример №1
В данном примере а равно 3 и switch по порядку сравнивает это значение с вариантами из case . Пропустив case 1 и case 2 , switch остановится на case 3 и выполнит alert( ‘a = 3’ ) . break в свою очередь закончит выполнение потока кода в конструкции. Если бы a не равнялось 1, 2 или 3, тогда выполнился бы код из default .
Пример №2
Если не использовать break тогда выполнение кода пойдет дальше и будут выполнены инструкции в case и default расположенные ниже — проверки в свою очередь будут проигнорированы.
В данном случае в console будет выведено:
Пример №3
В switch и case значения могут быть выражены по разному.
let a = 3 - 1; let b = 0; switch (++a) < case b + 1: alert('a = 1'); break; case b + 2: alert('a = 2'); break; case b + 3: alert('a = 3'); break; default: alert("a >3"); >
Здесь в switch выражение принимает значение 3, что соответствует b + 3 , таким образом будет выполнено alert(‘a = 3’) .
Группировка case
Благодаря тому, что break является прямым указанием на выход из switch и без него выполнение кода идет дальше, появляется возможность построения цепочек case , которые используют один и тот же код (инструкцию).
Пример №4
Проверка равенства в switch
Проверка соответствия выражения и valueN происходит по правилам строгого равенства (===) — значения должны быть одного типа.
Пример №5
let a = prompt("Введите число от 1 до 6"); switch (a)
Информация указанная в поле для ввода имеет тип данных строка, поэтому при вводе 2, 4, 6 выполниться alert(‘a четное число’) , так как в case ‘2’, ‘4’ и ‘6’ приведены в формату строки.
При вводе 1, 3, 5, выполниться default , так как в case 1, 3, 5 имеет формат число.
Итого
Конструкция switch сравнивает начальное выражение со случаями описанными внутри и исходя из этого выполняет нужный код. switch имеет в своем арсенале необязательные директивы break и default , что расширяет ее функционал и позволяет создавать цепочки case , а также задавать инструкции в том случае, если выражение не соответствует ни одному case .
Skypro — научим с нуля