|
1 |
| -# Type Conversions |
| 1 | +# Conversões de Tipo |
2 | 2 |
|
3 |
| -Most of the time, operators and functions automatically convert the values given to them to the right type. |
| 3 | +Na maior parte do tempo, operadores e funções convertem os valores dados a eles para o tipo certo automaticamente. |
4 | 4 |
|
5 |
| -For example, `alert` automatically converts any value to a string to show it. Mathematical operations convert values to numbers. |
| 5 | +Por exemplo, `alert` converte automaticamente qualquer valor para string antes de mostrá-lo. Operações matemáticas convertem os valores para números. |
6 | 6 |
|
7 |
| -There are also cases when we need to explicitly convert a value to the expected type. |
| 7 | +Também existem casos em que precisamos explicitamente de converter um valor para o tipo que precisamos. |
8 | 8 |
|
9 |
| -```smart header="Not talking about objects yet" |
10 |
| -In this chapter, we won't cover objects. For now we'll just be talking about primitives. |
| 9 | +```smart header="Não vamos falar de objetos" |
| 10 | +Nesse capítulo, não vamos falar sobre objetos. Por agora, vamos abordar apenas os tipos primitivos. |
11 | 11 |
|
12 |
| -Later, after we learn about objects, in the chapter <info:object-toprimitive> we'll see how objects fit in. |
| 12 | +Mais tarde, após abordarmos objetos no capítulo <info:object-toprimitive>, veremos como objetos se comportam em conversões de tipo. |
13 | 13 | ```
|
14 | 14 |
|
15 |
| -## String Conversion |
| 15 | +## Conversões para String |
16 | 16 |
|
17 |
| -String conversion happens when we need the string form of a value. |
| 17 | +As conversões para string acontecem quando precisamos da forma string de um valor. |
18 | 18 |
|
19 |
| -For example, `alert(value)` does it to show the value. |
| 19 | +Por exemplo, `alert(value)` faz isso para mostrar o valor. |
20 | 20 |
|
21 |
| -We can also call the `String(value)` function to convert a value to a string: |
| 21 | +Também podemos usar a função `String(value)` para converter um valor para string: |
22 | 22 |
|
23 | 23 | ```js run
|
24 | 24 | let value = true;
|
25 | 25 | alert(typeof value); // boolean
|
26 | 26 |
|
27 | 27 | *!*
|
28 |
| -value = String(value); // now value is a string "true" |
| 28 | +value = String(value); // agora value é uma string "true" |
29 | 29 | alert(typeof value); // string
|
30 | 30 | */!*
|
31 | 31 | ```
|
32 | 32 |
|
33 |
| -String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc. |
| 33 | +Conversões para string são as mais fáceis. `false` se torna `"false"`, `null` vira `"null"`, e assim por diante. |
| 34 | + |
| 35 | +## Conversões Numéricas |
34 | 36 |
|
35 |
| -## Numeric Conversion |
| 37 | +As conversões numéricas acontecem automaticamente em funções e expressões matemáticas. |
36 | 38 |
|
37 |
| -Numeric conversion happens in mathematical functions and expressions automatically. |
38 |
| - |
39 |
| -For example, when division `/` is applied to non-numbers: |
| 39 | +Por exemplo, quando `/` é usado com valores que não são números: |
40 | 40 |
|
41 | 41 | ```js run
|
42 |
| -alert( "6" / "2" ); // 3, strings are converted to numbers |
| 42 | +alert( "6" / "2" ); // 3, strings viram números |
43 | 43 | ```
|
44 | 44 |
|
45 |
| -We can use the `Number(value)` function to explicitly convert a `value` to a number: |
| 45 | +Podemos usar a função `Number(value)` para converter `value` para um número. |
46 | 46 |
|
47 | 47 | ```js run
|
48 | 48 | let str = "123";
|
49 | 49 | alert(typeof str); // string
|
50 | 50 |
|
51 |
| -let num = Number(str); // becomes a number 123 |
| 51 | +let num = Number(str); // vira o número 123 |
52 | 52 |
|
53 | 53 | alert(typeof num); // number
|
54 | 54 | ```
|
55 | 55 |
|
56 |
| -Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered. |
| 56 | +Conversões explícitas geralmente são obrigatórias quando estamos a ler um valor de uma fonte baseada em string - como um texto - mas esperamos receber um valor numérico. |
57 | 57 |
|
58 |
| -If the string is not a valid number, the result of such a conversion is `NaN`. For instance: |
| 58 | +Se a string não é um valor numérico válido, o resultado da conversão é `NaN`. Por exemplo: |
59 | 59 |
|
60 | 60 | ```js run
|
61 |
| -let age = Number("an arbitrary string instead of a number"); |
| 61 | +let age = Number("uma string ao invés de um número"); |
62 | 62 |
|
63 |
| -alert(age); // NaN, conversion failed |
| 63 | +alert(age); // NaN, a conversão falhou |
64 | 64 | ```
|
65 | 65 |
|
66 |
| -Numeric conversion rules: |
| 66 | +Regras de conversões numéricas: |
67 | 67 |
|
68 |
| -| Value | Becomes... | |
| 68 | +| Valor | Se torna... | |
69 | 69 | |-------|-------------|
|
70 | 70 | |`undefined`|`NaN`|
|
71 | 71 | |`null`|`0`|
|
72 |
| -|<code>true and false</code> | `1` and `0` | |
73 |
| -| `string` | Whitespaces from the start and end are removed. If the remaining string is empty, the result is `0`. Otherwise, the number is "read" from the string. An error gives `NaN`. | |
| 72 | +|<code>true e false</code>| `1` e `0` | |
| 73 | +| `string` | Espaços em branco do início e do fim são removidos. Se a string que sobrar for vazia, o resultado é `0`. Senão, o número é "lido" a partir da string. Um erro nos dá `NaN`| |
74 | 74 |
|
75 |
| -Examples: |
| 75 | +Exemplos: |
76 | 76 |
|
77 | 77 | ```js run
|
78 | 78 | alert( Number(" 123 ") ); // 123
|
79 |
| -alert( Number("123z") ); // NaN (error reading a number at "z") |
| 79 | +alert( Number("123z") ); // NaN (Erro ao ler um número em "z") |
80 | 80 | alert( Number(true) ); // 1
|
81 | 81 | alert( Number(false) ); // 0
|
82 | 82 | ```
|
83 | 83 |
|
84 |
| -Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`. |
| 84 | +Note que `null` e `undefined` se comportam de maneira diferente: `null` se torna zero, enquanto `undefined` vira `NaN`. |
85 | 85 |
|
86 |
| -Most mathematical operators also perform such conversion, we'll see that in the next chapter. |
| 86 | +A maioria dos operadores matemáticos também executam essa conversão, o que veremos no próximo capítulo. |
87 | 87 |
|
88 |
| -## Boolean Conversion |
| 88 | +## Conversões Booleanas |
89 | 89 |
|
90 |
| -Boolean conversion is the simplest one. |
| 90 | +Conversões booleanas são as mais simples de todas. |
91 | 91 |
|
92 |
| -It happens in logical operations (later we'll meet condition tests and other similar things) but can also be performed explicitly with a call to `Boolean(value)`. |
| 92 | +Acontecem em operações lógicas (depois veremos testes de condição e outras coisas similares), mas também podem acontecer explicitamente ao usar a função `Boolean(value)`. |
93 | 93 |
|
94 |
| -The conversion rule: |
| 94 | +A regra de conversão: |
95 | 95 |
|
96 |
| -- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`. |
97 |
| -- Other values become `true`. |
| 96 | +- Valores que são intuitivamente "vazios", como "0", uma string vazia (""), `null`, `undefined` e `NaN`, viram `false`. |
| 97 | +- Outros valores viram `true`. |
98 | 98 |
|
99 |
| -For instance: |
| 99 | +Por exemplo: |
100 | 100 |
|
101 | 101 | ```js run
|
102 | 102 | alert( Boolean(1) ); // true
|
103 | 103 | alert( Boolean(0) ); // false
|
104 | 104 |
|
105 |
| -alert( Boolean("hello") ); // true |
| 105 | +alert( Boolean("Olá") ); // true |
106 | 106 | alert( Boolean("") ); // false
|
107 | 107 | ```
|
108 | 108 |
|
109 |
| -````warn header="Please note: the string with zero `\"0\"` is `true`" |
110 |
| -Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript, a non-empty string is always `true`. |
| 109 | +````warn header="Note que uma string com um zero `\"0\"` é `true`" |
| 110 | +Algumas linguagens de programação (como PHP), tratam `\"0\"` como `false`. Mas no JavaScript, uma string não-vazia sempre é `true`. |
111 | 111 |
|
112 | 112 | ```js run
|
113 | 113 | alert( Boolean("0") ); // true
|
114 |
| -alert( Boolean(" ") ); // spaces, also true (any non-empty string is true) |
| 114 | +alert( Boolean(" ") ); // espaços também são true (toda string não-vazia se torna true) |
115 | 115 | ```
|
116 | 116 | ````
|
117 | 117 |
|
118 |
| -## Summary |
| 118 | +## Sumário |
119 | 119 |
|
120 |
| -The three most widely used type conversions are to string, to number, and to boolean. |
| 120 | +As três conversões mais comuns são para string, number e boolean. |
121 | 121 |
|
122 |
| -**`String Conversion`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values. |
| 122 | +**`Conversões para String`** -- Ocorrem quando mostramos algum valor. Podem ser explicitamente feitas com `String(value)`. As conversões para string geralmente são óbvias com tipos primitivos. |
123 | 123 |
|
124 |
| -**`Numeric Conversion`** -- Occurs in math operations. Can be performed with `Number(value)`. |
| 124 | +**`Conversões Numéricas`** -- Ocorrem em operações matemáticas. Podem ser feitas com `Number(value)`. |
125 | 125 |
|
126 |
| -The conversion follows the rules: |
| 126 | +A conversão segue as seguintes regras: |
127 | 127 |
|
128 |
| -| Value | Becomes... | |
| 128 | +| Valor | Se torna... | |
129 | 129 | |-------|-------------|
|
130 | 130 | |`undefined`|`NaN`|
|
131 | 131 | |`null`|`0`|
|
132 |
| -|<code>true / false</code> | `1 / 0` | |
133 |
| -| `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. | |
| 132 | +|<code>true / false</code>| `1 / 0` | |
| 133 | +| `string` | A string é lida "como ela é", espaços em branco do início e do fim são ignorados. Uma string vazia, vira `0`. Um erro nos dá `NaN`| |
134 | 134 |
|
135 |
| -**`Boolean Conversion`** -- Occurs in logical operations. Can be performed with `Boolean(value)`. |
| 135 | +**`Conversões Booleanas`** -- Ocorrem em operações lógicas. Podem ser feitas com `Boolean(value)`. |
136 | 136 |
|
137 |
| -Follows the rules: |
| 137 | +Seguem as regras: |
138 | 138 |
|
139 |
| -| Value | Becomes... | |
| 139 | +| Valor | Se torna... | |
140 | 140 | |-------|-------------|
|
141 | 141 | |`0`, `null`, `undefined`, `NaN`, `""` |`false`|
|
142 |
| -|any other value| `true` | |
| 142 | +|qualquer outro valor| `true` | |
143 | 143 |
|
144 | 144 |
|
145 |
| -Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are: |
| 145 | +A maior parte dessas regras são fáceis de entender e memorizar. Exceções notáveis em que as pessoas geralmente erram são: |
146 | 146 |
|
147 |
| -- `undefined` is `NaN` as a number, not `0`. |
148 |
| -- `"0"` and space-only strings like `" "` are true as a boolean. |
| 147 | +- `undefined` é `NaN` como número, não `0`. |
| 148 | +- `"0"` e strings só com espaços `" "` são `true` como booleanos. |
149 | 149 |
|
150 |
| -Objects aren't covered here. We'll return to them later in the chapter <info:object-toprimitive> that is devoted exclusively to objects after we learn more basic things about JavaScript. |
| 150 | +Objetos não são citados aqui. Retornaremos depois no capítulo <info:object-toprimitive> que é dedicado exclusivamente a objetos, após aprendermos coisas mais básicas de JavaScript. |
0 commit comments