You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/13-switch/2-rewrite-if-switch/solution.md
+3-3Lines changed: 3 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
The first two checks turn into two `case`. The third check is split into two cases:
1
+
Первые две проверки – обычный `case`, третья разделена на два `case`:
2
2
3
3
```js run
4
4
let a =+prompt('a?', '');
@@ -21,6 +21,6 @@ switch (a) {
21
21
}
22
22
```
23
23
24
-
Please note: the `break`at the bottom is not required. But we put it to make the code future-proof.
24
+
Обратите внимание: `break`внизу не обязателен, но ставится по «правилам хорошего тона».
25
25
26
-
In the future, there is a chance that we'd want to add one more `case`, for example `case 4`. And if we forget to add a break before it, at the end of `case 3`, there will be an error. So that's a kind of self-insurance.
26
+
Допустим, он не стоит. Есть шанс, что в будущем нам понадобится добавить в конец ещё один `case`, например `case 4`, и мы, вполне вероятно, забудем этот `break` поставить. В результате выполнение `case 2/case 3` продолжится на `case 4` и будет ошибка.
Copy file name to clipboardExpand all lines: 1-js/02-first-steps/13-switch/article.md
+32-32Lines changed: 32 additions & 32 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,14 +1,14 @@
1
-
# The "switch" statement
1
+
# Конструкция "switch"
2
2
3
-
A`switch`statement can replace multiple`if` checks.
3
+
Конструкция`switch`заменяет собой сразу несколько`if`.
4
4
5
-
It gives a more descriptive way to compare a value with multiple variants.
5
+
Она представляет собой более наглядный способ сравнить выражение сразу с несколькими вариантами.
6
6
7
-
## The syntax
7
+
## Синтаксис
8
8
9
-
The`switch`has one or more `case`blocks and an optional default.
9
+
Конструкция`switch`имеет один или более блок `case`и необязательный блок `default`.
10
10
11
-
It looks like this:
11
+
Выглядит она так:
12
12
13
13
```js no-beautify
14
14
switch(x) {
@@ -26,13 +26,13 @@ switch(x) {
26
26
}
27
27
```
28
28
29
-
-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.
30
-
-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`).
31
-
-If no case is matched then the `default` code is executed (if it exists).
29
+
-Переменная `x`проверяется на строгое равенство первому значению `value1`, затем второму `value2` и так далее.
30
+
-Если соответствие установлено – `switch`начинает выполняться от соответствующей директивы `case` и далее, до ближайшего `break` (или до конца`switch`).
31
+
-Если ни один `case` не совпал – выполняется (если есть) вариант `default`.
32
32
33
-
## An example
33
+
## Пример работы
34
34
35
-
An example of `switch` (the executed code is highlighted):
35
+
Пример использования `switch` (сработавший код выделен):
36
36
37
37
```js run
38
38
let a =2+2;
@@ -54,13 +54,13 @@ switch (a) {
54
54
}
55
55
```
56
56
57
-
Here the`switch`starts to compare `a`from the first `case` variant that is `3`. The match fails.
57
+
Здесь оператор`switch`последовательно сравнит `a`со всеми вариантами из `case`.
58
58
59
-
Then `4`. That's a match, so the execution starts from `case 4` until the nearest `break`.
59
+
Сначала `3`, затем – так как нет совпадения – `4`. Совпадение найдено, будет выполнен этот вариант, со строки `alert( 'Exactly!' )` и далее, до ближайшего `break`, который прервёт выполнение.
60
60
61
-
**If there is no `break`then the execution continues with the next`case` without any checks.**
61
+
**Если `break`нет, то выполнение пойдёт ниже по следующим`case`, при этом остальные проверки игнорируются.**
62
62
63
-
An example without`break`:
63
+
Пример без`break`:
64
64
65
65
```js run
66
66
let a =2+2;
@@ -79,18 +79,18 @@ switch (a) {
79
79
}
80
80
```
81
81
82
-
In the example above we'll see sequential execution of three `alert`s:
82
+
В примере выше последовательно выполнятся три `alert`:
83
83
84
84
```js
85
85
alert( 'Exactly!' );
86
86
alert( 'Too big' );
87
87
alert( "I don't know such values" );
88
88
```
89
89
90
-
````smart header="Any expression can be a `switch/case`argument"
91
-
Both`switch`and`case`allow arbitrary expressions.
90
+
````smart header="Любое выражение может быть `switch/case`аргументом"
91
+
Оба`switch`и`case`допускают любое выражение в качестве аргумента.
92
92
93
-
For example:
93
+
Например:
94
94
95
95
```js run
96
96
let a ="1";
@@ -107,14 +107,14 @@ switch (+a) {
107
107
alert("this doesn't run");
108
108
}
109
109
```
110
-
Here `+a`gives `1`, that's compared with `b + 1`in`case`, and the corresponding code is executed.
110
+
В этом примере выражение `+a`вычисляется в `1`, что совпадает с выражением `b + 1`в`case`, и следовательно, код в этом блоке будет выполнен.
111
111
````
112
112
113
-
## Grouping of "case"
113
+
## Группировка "case"
114
114
115
-
Several variants of `case` which share the same code can be grouped.
115
+
Несколько вариантов `case`, использующих один код, можно группировать.
116
116
117
-
For example, if we want the same code to run for `case 3` and `case 5`:
117
+
Для примера, выполним один и тот же код для `case 3` и `case 5`, сгруппировав их:
118
118
119
119
```js run no-beautify
120
120
let a = 2 + 2;
@@ -125,7 +125,7 @@ switch (a) {
125
125
break;
126
126
127
127
*!*
128
-
case 3: // (*) grouped two cases
128
+
case 3: // (*) группируем оба case
129
129
case 5:
130
130
alert('Wrong!');
131
131
alert("Why don't you take a math class?");
@@ -137,15 +137,15 @@ switch (a) {
137
137
}
138
138
```
139
139
140
-
Now both `3` and `5` show the same message.
140
+
Теперь оба варианта `3` и `5` выводят одно сообщение.
141
141
142
-
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`.
142
+
Возможность группировать `case` это побочный эффект того, как `switch/case` работает без `break`. Здесь выполнение `case 3` начинается со строки `(*)` и продолжается в `case 5`, потому отсутствует `break`.
143
143
144
-
## Type matters
144
+
## Тип имеет значение
145
145
146
-
Let's emphasize that the equality check is always strict. The values must be of the same type to match.
146
+
Нужно отметить, что проверка на равенство всегда строгая. Значения должны быть одного типа, чтобы выполнялось равенство.
147
147
148
-
For example, let's consider the code:
148
+
Для примера, давайте рассмотрим следующий код:
149
149
150
150
```js run
151
151
let arg = prompt("Enter a value?");
@@ -167,6 +167,6 @@ switch (arg) {
167
167
}
168
168
```
169
169
170
-
1. For `0`, `1`, the first `alert` runs.
171
-
2. For `2` the second `alert` runs.
172
-
3. 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.
170
+
1. Для `'0'` и `'1'` выполнится первый `alert`.
171
+
2. Для `'2'` -- второй `alert`.
172
+
3. Но для `3`, результат выполнения `prompt` будет строка `"3"`, которая не соответствует строгому равенству `===` с числом `3`. Таким образом, мы имеем "мёртвый код" в `case 3`! Выполнится вариант `default`.
0 commit comments