Skip to content

Commit f2b7444

Browse files
authored
Merge pull request #57 from odsantos/master
The "switch" statement
2 parents ea13ff9 + d63363a commit f2b7444

File tree

2 files changed

+210
-210
lines changed

2 files changed

+210
-210
lines changed
Lines changed: 57 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
1-
# The "switch" statement
1+
# A instrução "switch"
22

3-
A `switch` statement can replace multiple `if` checks.
3+
Uma instrução `switch` pode substituir muitas comparações `se`.
44

5-
It gives a more descriptive way to compare a value with multiple variants.
5+
Ela é uma forma mais descritiva de comparar um valor com múltiplas variantes.
66

7-
## The syntax
7+
## A sintaxe
88

9-
The `switch` has one or more `case` blocks and an optional default.
9+
O `switch` tem um ou mais blocos `case` (caso) e um `default` (padrão) opcional.
1010

11-
It looks like this:
11+
Tem uma apresentação similar a:
1212

1313
```js no-beautify
1414
switch(x) {
15-
case 'value1': // if (x === 'value1')
15+
case 'valor1': // if (x === 'valor1')
1616
...
1717
[break]
1818

19-
case 'value2': // if (x === 'value2')
19+
case 'valor2': // if (x === 'valor2')
2020
...
2121
[break]
2222

@@ -26,71 +26,71 @@ switch(x) {
2626
}
2727
```
2828

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 `case` (isto é, ao `valor1`), a seguir ao do 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 `case` correspondente, até ao próximo `break` (ou até ao fim do `switch`).
31+
- Se nenhum `case` é equiparado então o código em `default` é executado (se existir).
3232

33-
## An example
33+
## Um exemplo
3434

35-
An example of `switch` (the executed code is highlighted):
35+
Um exemplo de `switch` (o código executado está em destaque):
3636

3737
```js run
3838
let a = 2 + 2;
3939

4040
switch (a) {
4141
case 3:
42-
alert( 'Too small' );
42+
alert( 'Muito baixo' );
4343
break;
4444
*!*
4545
case 4:
46-
alert( 'Exactly!' );
46+
alert( 'Exacto!' );
4747
break;
4848
*/!*
4949
case 5:
50-
alert( 'Too large' );
50+
alert( 'Muito alto' );
5151
break;
5252
default:
53-
alert( "I don't know such values" );
53+
alert( "Não conheço tais valores" );
5454
}
5555
```
5656

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 `case`, que é `3`. A correspondência falha.
5858

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 correspondência, e assim a execução começa a partir do `case 4` até ao próximo `break`.
6060

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 `case` sem quaisquer verificações.**
6262

63-
An example without `break`:
63+
Um exemplo sem `break`:
6464

6565
```js run
6666
let a = 2 + 2;
6767

6868
switch (a) {
6969
case 3:
70-
alert( 'Too small' );
70+
alert( 'Muito baixo' );
7171
*!*
7272
case 4:
73-
alert( 'Exactly!' );
73+
alert( 'Exacto!' );
7474
case 5:
75-
alert( 'Too big' );
75+
alert( 'Muito alto' );
7676
default:
77-
alert( "I don't know such values" );
77+
alert( "Não conheço tais valores" );
7878
*/!*
7979
}
8080
```
8181

82-
In the example above we'll see sequential execution of three `alert`s:
82+
No exemplo acima, vemos uma execução sequential de três `alert`'s:
8383

8484
```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" );
8888
```
8989

90-
````smart header="Any expression can be a `switch/case` argument"
91-
Both `switch` and `case` allow arbitrary expressions.
90+
````smart header="Any expression can be a switch/case argument"
91+
Ambos `switch` e `case` permitem expressões arbitrárias.
9292
93-
For example:
93+
Por exemplo:
9494
9595
```js run
9696
let a = "1";
@@ -99,74 +99,75 @@ let b = 0;
9999
switch (+a) {
100100
*!*
101101
case b + 1:
102-
alert("this runs, because +a is 1, exactly equals b+1");
102+
alert("isto executa, porque +a é 1, e é exatamente igual a b+1");
103103
break;
104104
*/!*
105105
106106
default:
107-
alert("this doesn't run");
107+
alert("isto não executa");
108108
}
109109
```
110-
Here `+a` gives `1`, that's compared with `b + 1` in `case`, and the corresponding code is executed.
110+
Aqui `+a` `1`, o que é comparado a `b + 1` no `case`, e o código correspondente é executado.
111111
````
112112

113-
## Grouping of "case"
113+
## Grupos de "case"
114114

115-
Several variants of `case` which share the same code can be grouped.
115+
Múltiplas variantes de `case` que partihem o mesmo código podem ser agrupadas.
116116

117-
For example, if we want the same code to run for `case 3` and `case 5`:
117+
Por exemplo, se quisermos que o mesmo código corra por `case 3` e `case 5`:
118118

119119
```js run no-beautify
120120
let a = 2 + 2;
121121

122122
switch (a) {
123123
case 4:
124-
alert('Right!');
124+
alert('Certo!');
125125
break;
126126

127127
*!*
128-
case 3: // (*) grouped two cases
128+
case 3: // (*) dois cases agrupados
129129
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?");
132132
break;
133133
*/!*
134134

135135
default:
136-
alert('The result is strange. Really.');
136+
alert('O resultado é stranho. Realmente.');
137137
}
138138
```
139139

140-
Now both `3` and `5` show the same message.
140+
Agora ambos `3` e `5` mostram a mesma mensagem.
141141

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" cases é um efeito secundário de como `switch/case` funciona sem `break`. Aqui a execução do `case 3` começa pela linha `(*)` e prossegue pelo `case 5`, por não existir `break`.
143143

144-
## Type matters
144+
## O tipo importa
145145

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 correspondência.
147147

148-
For example, let's consider the code:
148+
Por exemplo, consideremos o código:
149149

150150
```js run
151-
let arg = prompt("Enter a value?");
151+
let arg = prompt("Insira um valor?");
152152
switch (arg) {
153153
case '0':
154154
case '1':
155-
alert( 'One or zero' );
155+
alert( 'Um ou zero' );
156156
break;
157157

158158
case '2':
159-
alert( 'Two' );
159+
alert( 'Dois' );
160160
break;
161161

162162
case 3:
163-
alert( 'Never executes!' );
163+
alert( 'Nunca executa!' );
164164
break;
165165
default:
166-
alert( 'An unknown value' );
166+
alert( 'Um valor desconhecido' );
167167
}
168168
```
169169

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

Comments
 (0)