|
1 |
| -# Type Conversions |
| 1 | +# Tipo Conversões |
2 | 2 |
|
3 |
| -Most of the time, operators and functions automatically convert the values given to them to the right type. |
| 3 | +Na maioria das vezes, os operadores e as funções convertem automaticamente os valores dados a eles para o tipo correto. |
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, o `alert` converte automaticamente qualquer valor para uma string para mostrá-lo. Operações matemáticas convertem valores em números. |
6 | 6 |
|
7 |
| -There are also cases when we need to explicitly convert a value to the expected type. |
| 7 | +Há também casos em que precisamos explicitamente converter um valor para o tipo esperado. |
8 | 8 |
|
9 | 9 | ```smart header="Not talking about objects yet"
|
10 |
| -In this chapter, we won't cover objects. Instead, we'll study primitives first. Later, after we learn about objects, we'll see how object conversion works in the chapter <info:object-toprimitive>. |
| 10 | +Neste capítulo, não cobriremos objectos. Em vez disso, estudaremos os primitivos primeiro. Mais tarde, depois de aprendermos sobre objetos, veremos como a conversão de objetos funciona no capítulo <info:object-toprimitive>. |
11 | 11 | ```
|
12 | 12 |
|
13 |
| -## ToString |
| 13 | +## Para String |
14 | 14 |
|
15 |
| -String conversion happens when we need the string form of a value. |
| 15 | +A conversão para strings acontece quando precisamos da forma de string de um valor. |
16 | 16 |
|
17 |
| -For example, `alert(value)` does it to show the value. |
18 |
| - |
19 |
| -We can also call the `String(value)` function to convert a value to a string: |
| 17 | +Por exemplo, `alert(value)` faz isso para mostrar o valor. |
20 | 18 |
|
| 19 | +Nós também podemos chamar a função `String(value)` para converter um valor em uma string: |
21 | 20 | ```js run
|
22 | 21 | let value = true;
|
23 |
| -alert(typeof value); // boolean |
| 22 | +alert(typeof value); // booleano |
24 | 23 |
|
25 | 24 | *!*
|
26 |
| -value = String(value); // now value is a string "true" |
| 25 | +value = String(value); // agora value é uma string "true" |
27 | 26 | alert(typeof value); // string
|
28 | 27 | */!*
|
29 | 28 | ```
|
30 | 29 |
|
31 |
| -String conversion is mostly obvious. A `false` becomes `"false"`, `null` becomes `"null"`, etc. |
| 30 | +A conversão de strings é mais óbvia. Uma `false` torna-se `"false"`, `null` torna-se `"null"`, etc. |
32 | 31 |
|
33 |
| -## ToNumber |
| 32 | +## Para Número |
34 | 33 |
|
35 |
| -Numeric conversion happens in mathematical functions and expressions automatically. |
| 34 | +A conversão numérica acontece automaticamente em funções e expressões matemáticas. |
36 | 35 |
|
37 |
| -For example, when division `/` is applied to non-numbers: |
| 36 | +Por exemplo, quando a divisão `/` é aplicada para não-numeros: |
38 | 37 |
|
39 | 38 | ```js run
|
40 |
| -alert( "6" / "2" ); // 3, strings are converted to numbers |
| 39 | +alert( "6" / "2" ); // 3, strings são convertidas para números |
41 | 40 | ```
|
42 | 41 |
|
43 |
| -We can use the `Number(value)` function to explicitly convert a `value` to a number: |
| 42 | +Podemos usar a função `Number(value)` para converter explicitamente um `value` para um número: |
44 | 43 |
|
45 | 44 | ```js run
|
46 | 45 | let str = "123";
|
47 | 46 | alert(typeof str); // string
|
48 | 47 |
|
49 |
| -let num = Number(str); // becomes a number 123 |
| 48 | +let num = Number(str); // torna-se um número 123 |
| 49 | + |
| 50 | +alert(typeof num); // número |
50 | 51 |
|
51 |
| -alert(typeof num); // number |
52 | 52 | ```
|
53 | 53 |
|
54 |
| -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. |
| 54 | +A conversão explícita é normalmente necessária quando lemos um valor de uma fonte baseada em string como um formulário de texto, mas esperamos que um número seja inserido. |
55 | 55 |
|
56 |
| -If the string is not a valid number, the result of such a conversion is `NaN`. For instance: |
| 56 | +Se a cadeia não for um número válido, o resultado de tal conversão é `NaN'. Por exemplo: |
57 | 57 |
|
58 | 58 | ```js run
|
59 |
| -let age = Number("an arbitrary string instead of a number"); |
| 59 | +let age = Number("uma string arbitrária em vez de um número"); |
60 | 60 |
|
61 |
| -alert(age); // NaN, conversion failed |
| 61 | +alert(age); // NaN, conversão falhou |
62 | 62 | ```
|
63 | 63 |
|
64 |
| -Numeric conversion rules: |
| 64 | +Regras de conversão numéricas: |
65 | 65 |
|
66 |
| -| Value | Becomes... | |
| 66 | +| Valor | Torna-se... | |
67 | 67 | |-------|-------------|
|
68 | 68 | |`undefined`|`NaN`|
|
69 | 69 | |`null`|`0`|
|
70 | 70 | |<code>true and false</code> | `1` and `0` |
|
71 |
| -| `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`. | |
| 71 | +| `string` | Espaços em branco do ínicio e fim são removidos. Se a string restante estiver vazia, o resultado é `0`. Casa contrário, o número é "lido" a partir da string. Um erro dá `NaN`. | |
72 | 72 |
|
73 |
| -Examples: |
| 73 | +Exemplos: |
74 | 74 |
|
75 | 75 | ```js run
|
76 | 76 | alert( Number(" 123 ") ); // 123
|
77 |
| -alert( Number("123z") ); // NaN (error reading a number at "z") |
| 77 | +alert( Number("123z") ); // NaN (erro ao ler um número em "z") |
78 | 78 | alert( Number(true) ); // 1
|
79 | 79 | alert( Number(false) ); // 0
|
80 | 80 | ```
|
81 | 81 |
|
82 |
| -Please note that `null` and `undefined` behave differently here: `null` becomes zero while `undefined` becomes `NaN`. |
| 82 | +Por favor note que `null` e `undefined` se comportam diferente aqui: `null` torna-se zero enquanto `undefined` torna-se `NaN`. |
83 | 83 |
|
84 |
| -````smart header="Addition '+' concatenates strings" |
85 |
| -Almost all mathematical operations convert values to numbers. A notable exception is addition `+`. If one of the added values is a string, the other one is also converted to a string. |
| 84 | +````smart header="Adição '+' concatenações de strings" |
| 85 | +Quase todas as operações matemáticas convertem valores em números. Uma exceção notável é a adição `+`. Se um dos valores adicionados é uma string, a outra também é convertida para uma string. |
86 | 86 |
|
87 |
| -Then, it concatenates (joins) them: |
| 87 | +Então, ele concatena (junta-se a eles): |
88 | 88 |
|
89 | 89 | ```js run
|
90 |
| -alert( 1 + '2' ); // '12' (string to the right) |
91 |
| -alert( '1' + 2 ); // '12' (string to the left) |
| 90 | +alert( 1 + '2' ); // '12' (string para a direita) |
| 91 | +alert( '1' + 2 ); // '12' (string para a esquerda) |
92 | 92 | ```
|
93 | 93 |
|
94 |
| -This only happens when at least one of the arguments is a string. Otherwise, values are converted to numbers. |
| 94 | +Isso só acontece quando pelo menos um dos argumentos é uma string. Caso contrário, os valores são convertidos em números. |
95 | 95 | ````
|
96 | 96 |
|
97 |
| -## ToBoolean |
| 97 | +## Para Booleano |
98 | 98 |
|
99 |
| -Boolean conversion is the simplest one. |
| 99 | +A conversão booleana é a mais simples. |
100 | 100 |
|
101 |
| -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)`. |
| 101 | +Isso acontece em operações lógicas (mais tarde vamos encontrar testes de condição e outras coisas similares), mas também pode ser feito explicitamente com uma chamada para `Boolean(value)`. |
102 | 102 |
|
103 |
| -The conversion rule: |
| 103 | +A regra de conversão: |
104 | 104 |
|
105 |
| -- Values that are intuitively "empty", like `0`, an empty string, `null`, `undefined`, and `NaN`, become `false`. |
106 |
| -- Other values become `true`. |
| 105 | +- Valores que são intuitivamente "vazios", como `0`, uma string vazia, `null`, `undefined`, e `NaN`, tornam-se `false`. |
| 106 | +- Outros valores tornam-se `true`. |
107 | 107 |
|
108 |
| -For instance: |
| 108 | +Por exemplo: |
109 | 109 |
|
110 | 110 | ```js run
|
111 | 111 | alert( Boolean(1) ); // true
|
112 | 112 | alert( Boolean(0) ); // false
|
113 | 113 |
|
114 |
| -alert( Boolean("hello") ); // true |
| 114 | +alert( Boolean("olá") ); // true |
115 | 115 | alert( Boolean("") ); // false
|
116 | 116 | ```
|
117 | 117 |
|
118 |
| -````warn header="Please note: the string with zero `\"0\"` is `true`" |
119 |
| -Some languages (namely PHP) treat `"0"` as `false`. But in JavaScript, a non-empty string is always `true`. |
| 118 | +````warn header="Por favor note: a string com `\"0\"` é `true`" |
| 119 | +Algumas linguagens (especificamente PHP) tratam `"0"` como `false`. Mas em JavaScript, uma string não vazia é sempre `true`. |
120 | 120 |
|
121 | 121 | ```js run
|
122 | 122 | alert( Boolean("0") ); // true
|
123 |
| -alert( Boolean(" ") ); // spaces, also true (any non-empty string is true) |
| 123 | +alert( Boolean(" ") ); // espaços, também true (qualquer string não vaiza é true) |
124 | 124 | ```
|
125 | 125 | ````
|
126 | 126 |
|
127 | 127 |
|
128 |
| -## Summary |
| 128 | +## Resumo |
129 | 129 |
|
130 |
| -The three most widely used type conversions are to string, to number, and to boolean. |
| 130 | +As três conversões de tipo mais usadas são para string, para número e para booleano. |
131 | 131 |
|
132 |
| -**`ToString`** -- Occurs when we output something. Can be performed with `String(value)`. The conversion to string is usually obvious for primitive values. |
| 132 | +**`Para String`** -- Ocorre quando produzimos algo. Pode ser executado com `String(value)`. A conversão para string é geralmente óbvia para valores primitivos. |
133 | 133 |
|
134 |
| -**`ToNumber`** -- Occurs in math operations. Can be performed with `Number(value)`. |
| 134 | +**`Para Número`** -- Ocorre em operações matemáticas. Pode ser executado com `Number(value)`. |
135 | 135 |
|
136 |
| -The conversion follows the rules: |
| 136 | +Regras de conversão numéricas: |
137 | 137 |
|
138 |
| -| Value | Becomes... | |
| 138 | +| Valor | Torna-se... | |
139 | 139 | |-------|-------------|
|
140 | 140 | |`undefined`|`NaN`|
|
141 | 141 | |`null`|`0`|
|
142 |
| -|<code>true / false</code> | `1 / 0` | |
143 |
| -| `string` | The string is read "as is", whitespaces from both sides are ignored. An empty string becomes `0`. An error gives `NaN`. | |
| 142 | +|<code>true and false</code> | `1` and `0` | |
| 143 | +| `string` | Espaços em branco do ínicio e fim são removidos. Se a string restante estiver vazia, o resultado é `0`. Casa contrário, o número é "lido" a partir da string. Um erro dá `NaN`. | |
144 | 144 |
|
145 |
| -**`ToBoolean`** -- Occurs in logical operations. Can be performed with `Boolean(value)`. |
| 145 | +**`Para Booleano`** -- Ocorre em operações lógicas. Pode ser executado com `Boolean(value)`. |
146 | 146 |
|
147 |
| -Follows the rules: |
| 147 | +Segue as regras: |
148 | 148 |
|
149 |
| -| Value | Becomes... | |
| 149 | +| Valor | Torna-se... | |
150 | 150 | |-------|-------------|
|
151 | 151 | |`0`, `null`, `undefined`, `NaN`, `""` |`false`|
|
152 |
| -|any other value| `true` | |
| 152 | +|qualquer outro valor| `true` | |
153 | 153 |
|
154 | 154 |
|
155 |
| -Most of these rules are easy to understand and memorize. The notable exceptions where people usually make mistakes are: |
| 155 | +A maioria destas regras são fáceis de entender e memorizar. As exceções notáveis onde as pessoas normalmente cometem erros são: |
156 | 156 |
|
157 |
| -- `undefined` is `NaN` as a number, not `0`. |
158 |
| -- `"0"` and space-only strings like `" "` are true as a boolean. |
| 157 | +- `undefined` is `NaN` como um número, não `0`. |
| 158 | +- `"0"` e strings com espaço apenas `" "` são verdadeiras como booleanas. |
159 | 159 |
|
160 |
| -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. |
| 160 | +Objetos não são abordados aqui. Voltaremos a eles mais tarde no capítulo <info:object-toprimitive> que é dedicado exclusivamente a objetos, depois de aprendermos coisas mais básicas sobre JavaScript. |
0 commit comments