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
A `switch`statement can replace multiple `if` checks.
3
+
Uma instrução `switch`pode substituir muitas comparações `se`.
4
4
5
-
It gives a more descriptive way to compare a value with multiple variants.
5
+
Ela dá uma forma mais descritiva de comparar um valor com múltiplas variantes.
6
6
7
-
## The syntax
7
+
## A sintaxe
8
8
9
-
The`switch`has one or more `case` blocks and an optional default.
9
+
O`switch`tem um ou mais blocos `caso` e um `defeito` opcional.
10
10
11
-
It looks like this:
11
+
Tem uma apresentação similar a:
12
12
13
13
```js no-beautify
14
14
switch(x) {
15
-
case'value1': // if (x === 'value1')
15
+
case'valor1': // if (x === 'valor1')
16
16
...
17
17
[break]
18
18
19
-
case'value2': // if (x === 'value2')
19
+
case'valor2': // if (x === 'valor2')
20
20
...
21
21
[break]
22
22
@@ -26,71 +26,71 @@ 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
+
-O valor de`x`é comparado por meio de uma igualdade exata ao valor do primeiro `caso` (isto é, ao `valor1`), a seguir ao segundo (`valor2`) e assim sucessivamente.
30
+
-Se uma igualdade é encontrada, o `switch`começa a executar o código a partir do início do `caso` correspondente, até ao próximo`break` (ou até ao fim do`switch`).
31
+
-Se nenhum caso é equiparado então o código em `defeito` é executado (se existir).
32
32
33
-
## An example
33
+
## Um examplo
34
34
35
-
An example of`switch` (the executed code is highlighted):
35
+
Um examplo de`switch` (o código executado code está em destaque):
36
36
37
37
```js run
38
38
let a =2+2;
39
39
40
40
switch (a) {
41
41
case3:
42
-
alert( 'Too small' );
42
+
alert( 'Muito baixo' );
43
43
break;
44
44
*!*
45
45
case4:
46
-
alert( 'Exactly!' );
46
+
alert( 'Exacto!' );
47
47
break;
48
48
*/!*
49
49
case5:
50
-
alert( 'Too large' );
50
+
alert( 'Muito alto' );
51
51
break;
52
52
default:
53
-
alert( "I don't know such values" );
53
+
alert( "Não conheço tais valores" );
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
+
Aqui o`switch`começa por comparar`a`à variante no primeiro `caso`, que é `3`. A equiparação falha.
58
58
59
-
Then `4`. That's a match, so the execution starts from `case 4`until the nearest`break`.
59
+
Então a `4`. Existe uma equiparação, e assim a execução começa a partir do `caso 4`até ao próximo`break`.
60
60
61
-
**If there is no`break`then the execution continues with the next `case` without any checks.**
61
+
**Se não existir um`break`então a execução continua pelo próximo `caso` sem quaisquer verificações.**
62
62
63
-
An example without`break`:
63
+
Um examplo sem`break`:
64
64
65
65
```js run
66
66
let a =2+2;
67
67
68
68
switch (a) {
69
69
case3:
70
-
alert( 'Too small' );
70
+
alert( 'Muito baixo' );
71
71
*!*
72
72
case4:
73
-
alert( 'Exactly!' );
73
+
alert( 'Exacto!' );
74
74
case5:
75
-
alert( 'Too big' );
75
+
alert( 'Muito alto' );
76
76
default:
77
-
alert( "I don't know such values" );
77
+
alert( "Não conheço tais valores" );
78
78
*/!*
79
79
}
80
80
```
81
81
82
-
In the example above we'll see sequential execution of three`alert`s:
82
+
No examplo acima, vemos uma execução sequential de três`alert`s:
83
83
84
84
```js
85
-
alert( 'Exactly!' );
86
-
alert( 'Too big' );
87
-
alert( "I don't know such values" );
85
+
alert( 'Exacto!' );
86
+
alert( 'Muito alto' );
87
+
alert( "Não conheço tais valores" );
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="Qualquer expressão pode servir de argumento para `switch/case` "
alert("this runs, because +a is 1, exactly equals b+1");
102
+
alert("isto executa, porque +a é 1, e é exatamente igual a b+1");
103
103
break;
104
104
*/!*
105
105
106
106
default:
107
-
alert("this doesn't run");
107
+
alert("isto não executa");
108
108
}
109
109
```
110
-
Here`+a`gives`1`, that's compared with `b + 1`in `case`, and the corresponding code is executed.
110
+
Aqui`+a`dá`1`, o que é comparado a `b + 1`no `caso`, e o código correspondente é executado.
111
111
````
112
112
113
-
## Grouping of "case"
113
+
## Grupos de "caso"
114
114
115
-
Several variants of `case` which share the same code can be grouped.
115
+
Múltiplas variantes de `caso` que partihem o mesmo código podem ser agrupadas.
116
116
117
-
For example, if we want the same code to run for `case 3` and `case 5`:
117
+
Por examplo, se quisermos que o mesmo código corra por `caso 3` e `caso 5`:
118
118
119
119
```js run no-beautify
120
120
let a = 2 + 2;
121
121
122
122
switch (a) {
123
123
case 4:
124
-
alert('Right!');
124
+
alert('Certo!');
125
125
break;
126
126
127
127
*!*
128
-
case 3: // (*) grouped two cases
128
+
case 3: // (*) dois casos agrupados
129
129
case 5:
130
-
alert('Wrong!');
131
-
alert("Why don't you take a math class?");
130
+
alert('Errado!');
131
+
alert("Porque não tem aulas de matemática?");
132
132
break;
133
133
*/!*
134
134
135
135
default:
136
-
alert('The result is strange. Really.');
136
+
alert('O resultado é stranho. Realmente.');
137
137
}
138
138
```
139
139
140
-
Now both `3` and `5` show the same message.
140
+
Agora ambos `3` e `5` mostram a mesma mensagem.
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
+
A habilidade para "agrupar" casos é um efeito secundário de como `switch/case` funciona sem `break`. Aqui a execução do `caso 3` começa pela linha `(*)` e prossegue pelo `caso 5`, por não existir `break`.
143
143
144
-
## Type matters
144
+
## O tipo importa
145
145
146
-
Let's emphasize that the equality check is always strict. The values must be of the same type to match.
146
+
Vamos emfatizar que a verificação da igualdade é sempre exata. Os valores devem também ser do mesmo tipo para existir equiparação.
147
147
148
-
For example, let's consider the code:
148
+
Por examplo, consideremos o código:
149
149
150
150
```js run
151
-
let arg = prompt("Enter a value?");
151
+
let arg = prompt("Insira um valor?");
152
152
switch (arg) {
153
153
case '0':
154
154
case '1':
155
-
alert( 'One or zero' );
155
+
alert( 'Um ou zero' );
156
156
break;
157
157
158
158
case '2':
159
-
alert( 'Two' );
159
+
alert( 'Dois' );
160
160
break;
161
161
162
162
case 3:
163
-
alert( 'Never executes!' );
163
+
alert( 'Nunca executa!' );
164
164
break;
165
165
default:
166
-
alert( 'An unknown value' );
166
+
alert( 'Um valor desconhecido' );
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. Para `0`, `1`, o primeiro `alert` executa.
171
+
2. Para `2` o segundo `alert` corre.
172
+
3. Mas para `3`, o resultado do `prompt` á a string `"3"`, que não é estritamente igual `===` ao número `3`. Assim temos código não
173
+
executável em `case 3`! A variante `default` será executada.
0 commit comments