From f3fb7d2927a16e702ac7683957ff2981c86d31c5 Mon Sep 17 00:00:00 2001 From: odsantos Date: Tue, 22 Oct 2019 05:42:38 +0100 Subject: [PATCH 1/3] translate '01-object' directory files --- .../01-object/2-hello-object/solution.md | 2 - .../01-object/2-hello-object/task.md | 14 +- .../01-object/3-is-empty/_js.view/solution.js | 2 +- .../01-object/3-is-empty/_js.view/test.js | 4 +- .../01-object/3-is-empty/solution.md | 2 +- .../01-object/3-is-empty/task.md | 13 +- .../01-object/4-const-object/solution.md | 10 +- .../01-object/4-const-object/task.md | 6 +- .../01-object/5-sum-object/task.md | 8 +- .../8-multiply-numeric/_js.view/source.js | 6 +- .../8-multiply-numeric/_js.view/test.js | 8 +- .../01-object/8-multiply-numeric/task.md | 20 +- 1-js/04-object-basics/01-object/article.md | 473 +++++++++--------- 1-js/04-object-basics/index.md | 2 +- 14 files changed, 281 insertions(+), 289 deletions(-) diff --git a/1-js/04-object-basics/01-object/2-hello-object/solution.md b/1-js/04-object-basics/01-object/2-hello-object/solution.md index 60083b963..dff006076 100644 --- a/1-js/04-object-basics/01-object/2-hello-object/solution.md +++ b/1-js/04-object-basics/01-object/2-hello-object/solution.md @@ -1,5 +1,4 @@ - ```js let user = {}; user.name = "John"; @@ -7,4 +6,3 @@ user.surname = "Smith"; user.name = "Pete"; delete user.name; ``` - diff --git a/1-js/04-object-basics/01-object/2-hello-object/task.md b/1-js/04-object-basics/01-object/2-hello-object/task.md index 2841a058f..c0e296444 100644 --- a/1-js/04-object-basics/01-object/2-hello-object/task.md +++ b/1-js/04-object-basics/01-object/2-hello-object/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Hello, object +# Olá, objeto -Write the code, one line for each action: +Escreva o código, uma ação por linha: -1. Create an empty object `user`. -2. Add the property `name` with the value `John`. -3. Add the property `surname` with the value `Smith`. -4. Change the value of the `name` to `Pete`. -5. Remove the property `name` from the object. +1. Crie um objeto vazio (*empty object*) `user`. +2. Adicione a propriedade `name` com o valor `John`. +3. Adicione a propriedade `surname` com o valor `Smith`. +4. Altere o valor de `name` para `Pete`. +5. Remova a propriedade `name` do objeto. diff --git a/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js b/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js index db3283e49..ca7dc324e 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js +++ b/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js @@ -1,6 +1,6 @@ function isEmpty(obj) { for (let key in obj) { - // if the loop has started, there is a property + // se o laço começou, existe uma propriedade return false; } return true; diff --git a/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js b/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js index 4db5efabe..400577698 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js +++ b/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js @@ -1,9 +1,9 @@ describe("isEmpty", function() { - it("returns true for an empty object", function() { + it("retorna verdadeiro para um objeto vazio", function() { assert.isTrue(isEmpty({})); }); - it("returns false if a property exists", function() { + it("retorna falso se uma propriedade existir", function() { assert.isFalse(isEmpty({ anything: false })); diff --git a/1-js/04-object-basics/01-object/3-is-empty/solution.md b/1-js/04-object-basics/01-object/3-is-empty/solution.md index b876973b5..6c328fc39 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/solution.md +++ b/1-js/04-object-basics/01-object/3-is-empty/solution.md @@ -1 +1 @@ -Just loop over the object and `return false` immediately if there's at least one property. +Simplemente, percorra (*loop over*) o objeto e imediatamente `return false` se pelo menos houver uma propriedade. diff --git a/1-js/04-object-basics/01-object/3-is-empty/task.md b/1-js/04-object-basics/01-object/3-is-empty/task.md index c438d36a2..a499e6eb7 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/task.md +++ b/1-js/04-object-basics/01-object/3-is-empty/task.md @@ -2,19 +2,18 @@ importance: 5 --- -# Check for emptiness +# Verifique por vazio (*emptiness*) -Write the function `isEmpty(obj)` which returns `true` if the object has no properties, `false` otherwise. - -Should work like that: +Escreva a função `isEmpty(obj)`, que retorna `true` se o objeto não tiver propriedades, e `false` caso contrário. +Deve assim funcionar: ```js let schedule = {}; -alert( isEmpty(schedule) ); // true +alert( isEmpty(schedule) ); // verdadeiro -schedule["8:30"] = "get up"; +schedule["8:30"] = "levante-se"; -alert( isEmpty(schedule) ); // false +alert( isEmpty(schedule) ); // falso ``` diff --git a/1-js/04-object-basics/01-object/4-const-object/solution.md b/1-js/04-object-basics/01-object/4-const-object/solution.md index f73c2f92b..9cb150373 100644 --- a/1-js/04-object-basics/01-object/4-const-object/solution.md +++ b/1-js/04-object-basics/01-object/4-const-object/solution.md @@ -1,8 +1,8 @@ -Sure, it works, no problem. +Com certeza, funciona, sem problemas. -The `const` only protects the variable itself from changing. +A `const` apenas protege a própria variável contra alterações. -In other words, `user` stores a reference to the object. And it can't be changed. But the content of the object can. +Por outras palavras, `user` armazena uma referência ao objeto. E não pode ser alterada. Mas, o conteúdo do objeto pode. ```js run const user = { @@ -10,10 +10,10 @@ const user = { }; *!* -// works +// funciona user.name = "Pete"; */!* -// error +// erro user = 123; ``` diff --git a/1-js/04-object-basics/01-object/4-const-object/task.md b/1-js/04-object-basics/01-object/4-const-object/task.md index a9aada631..a0a1709dc 100644 --- a/1-js/04-object-basics/01-object/4-const-object/task.md +++ b/1-js/04-object-basics/01-object/4-const-object/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Constant objects? +# Objetos constantes? -Is it possible to change an object declared with `const`? What do you think? +É possível alterar um objeto declarado com `const`? O que acha? ```js const user = { @@ -12,7 +12,7 @@ const user = { }; *!* -// does it work? +// isto funciona? user.name = "Pete"; */!* ``` diff --git a/1-js/04-object-basics/01-object/5-sum-object/task.md b/1-js/04-object-basics/01-object/5-sum-object/task.md index 7e3e048d0..b0caee202 100644 --- a/1-js/04-object-basics/01-object/5-sum-object/task.md +++ b/1-js/04-object-basics/01-object/5-sum-object/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Sum object properties +# Soma das propriedades de um objeto -We have an object storing salaries of our team: +Temos um objeto armazenando salários da nossa equipa: ```js let salaries = { @@ -14,6 +14,6 @@ let salaries = { } ``` -Write the code to sum all salaries and store in the variable `sum`. Should be `390` in the example above. +Escreva o código para somar todos os salários e armazenar na variável `sum`. Para o exemplo acima, deverá ser `390`. -If `salaries` is empty, then the result must be `0`. \ No newline at end of file +Se `salaries` for vazio, então o resultado deve ser `0`. \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js index a02b1e1cb..f2ffe4901 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js @@ -1,17 +1,17 @@ let menu = { width: 200, height: 300, - title: "My menu" + title: "O meu menu" }; function multiplyNumeric(obj) { - /* your code */ + /* o seu código */ } multiplyNumeric(menu); -alert( "menu width=" + menu.width + " height=" + menu.height + " title=" + menu.title ); +alert( "largura do menu=" + menu.width + " altura=" + menu.height + " título=" + menu.title ); diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js index 064e5414f..2ba28f769 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js @@ -1,17 +1,17 @@ describe("multiplyNumeric", function() { - it("multiplies all numeric properties by 2", function() { + it("multiplica todas as propriedades numéricas por 2", function() { let menu = { width: 200, height: 300, - title: "My menu" + title: "O meu menu" }; let result = multiplyNumeric(menu); assert.equal(menu.width, 400); assert.equal(menu.height, 600); - assert.equal(menu.title, "My menu"); + assert.equal(menu.title, "O meu menu"); }); - it("returns nothing", function() { + it("não retorna nada", function() { assert.isUndefined( multiplyNumeric({}) ); }); diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/task.md b/1-js/04-object-basics/01-object/8-multiply-numeric/task.md index 33eb89220..54fa7fceb 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/task.md +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/task.md @@ -2,32 +2,30 @@ importance: 3 --- -# Multiply numeric properties by 2 +# Multiplica as propriedades numéricas por 2 -Create a function `multiplyNumeric(obj)` that multiplies all numeric properties of `obj` by `2`. +Crie uma função `multiplyNumeric(obj)` que multiplica todas as proriedades numéricas de `obj` por `2`. -For instance: +Por exemplo: ```js -// before the call +// antes da chamada let menu = { width: 200, height: 300, - title: "My menu" + title: "O meu menu" }; multiplyNumeric(menu); -// after the call +// depois da chamada menu = { width: 400, height: 600, - title: "My menu" + title: "O meu menu" }; ``` -Please note that `multiplyNumeric` does not need to return anything. It should modify the object in-place. - -P.S. Use `typeof` to check for a number here. - +Por favor, note que `multiplyNumeric` não precisa de retornar nada. Deve modificar o próprio objecto. +P.S. Use `typeof` para verificar por um número aqui. diff --git a/1-js/04-object-basics/01-object/article.md b/1-js/04-object-basics/01-object/article.md index 00706750c..baba98e3a 100644 --- a/1-js/04-object-basics/01-object/article.md +++ b/1-js/04-object-basics/01-object/article.md @@ -1,60 +1,60 @@ -# Objects +# Objetos -As we know from the chapter , there are seven data types in JavaScript. Six of them are called "primitive", because their values contain only a single thing (be it a string or a number or whatever). +Como sabemos, pelo capítulo , existem sete tipos de dados em JavaScript. Seis deles são chamados de "primitivos", porque os seus valores apenas contêm uma única coisa (seja ela uma cadeia-de-carateres [*string*], um número, ou o que for). -In contrast, objects are used to store keyed collections of various data and more complex entities. In JavaScript, objects penetrate almost every aspect of the language. So we must understand them first before going in-depth anywhere else. +Em contraste, objetos são empregues para armazenar por meio de uma chave, coleções de vários dados e entidades mais complexas. Em JavaScript, objetos penetram em quase todos os aspetos da linguagem. Portanto, devemos primeiro compreendê-los antes de nos envolvermos detalhadamente em algo mais. -An object can be created with figure brackets `{…}` with an optional list of *properties*. A property is a "key: value" pair, where `key` is a string (also called a "property name"), and `value` can be anything. +Um objeto pode ser criado por chavetas `{…}`, com uma lista opcional de *propriedades*. Uma propriedade é um par "key: value" (chave: valor), onde `key` é uma *string* (também chamada de "nome da propriedade"), e `value` pode ser qualquer coisa. -We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It's easy to find a file by its name or add/remove a file. +Podemos imaginar um objeto como um fichário com ficheiros assinados. Cada peça de informação, é armazenada no seu ficheiro ligada a uma chave. É fácil encontrar um ficheiro através do seu nome, ou adicionar/remover um ficheiro. ![](object.svg) -An empty object ("empty cabinet") can be created using one of two syntaxes: +Um objeto vazio ("fichário vazio"), pode ser criado por uma de duas sintaxes: ```js -let user = new Object(); // "object constructor" syntax -let user = {}; // "object literal" syntax +let user = new Object(); // sintaxe de "construtor de objetos" +let user = {}; // sintaxe de "objeto literal" ``` ![](object-user-empty.svg) -Usually, the figure brackets `{...}` are used. That declaration is called an *object literal*. +Geralmente, são utilizadas as chavetas `{...}`. Essa declaração é chamada de *objeto literal*. -## Literals and properties +## Literais e propriedades -We can immediately put some properties into `{...}` as "key: value" pairs: +Podemos imediatamente colocar algumas propriedades dentro das `{...}` como pares "chave: valor" (*key: value*): ```js -let user = { // an object - name: "John", // by key "name" store value "John" - age: 30 // by key "age" store value 30 +let user = { // um objeto + name: "John", // na chave "name" armazene o valor "John" + age: 30 // na chave "age" armazene o valor 30 }; ``` -A property has a key (also known as "name" or "identifier") before the colon `":"` and a value to the right of it. +Uma propriedade, tem uma chave (*key* - também conhecida por "nome" ou "identificador") antes dos dois-pontos `":"` e um valor à sua direita. -In the `user` object, there are two properties: +No objeto `user`, existem duas propriedades: -1. The first property has the name `"name"` and the value `"John"`. -2. The second one has the name `"age"` and the value `30`. +1. A primeira, tem o nome `"name"` e o valor `"John"`. +2. A segunda, tem o nome `"age"` e o valor `30`. -The resulting `user` object can be imagined as a cabinet with two signed files labeled "name" and "age". +O objeto `user` resultante, pode ser imaginado como um fichário com dois ficheiros assinados com as etiquetas "*name*" e "*age*". ![user object](object-user.svg) -We can add, remove and read files from it any time. +Podemos adicionar, remover e ler ficheiros dele a qualquer altura. -Property values are accessible using the dot notation: +Valores de propriedades podem ser acedidos usando a notação por ponto (*dot notation*): ```js -// get fields of the object: +// obtenha os campos do objeto: alert( user.name ); // John alert( user.age ); // 30 ``` -The value can be of any type. Let's add a boolean one: +O valor pode ser de qualquer tipo. Vamos adicionar um booleano: ```js user.isAdmin = true; @@ -62,7 +62,7 @@ user.isAdmin = true; ![user object 2](object-user-isadmin.svg) -To remove a property, we can use `delete` operator: +Para remover uma propriedade, podemos usar o operador `delete`: ```js delete user.age; @@ -70,69 +70,70 @@ delete user.age; ![user object 3](object-user-delete.svg) -We can also use multiword property names, but then they must be quoted: +Podemos também usar nomes de propriedades com múltiplas palavras, mas aí eles têm de estar entre aspas: ```js let user = { name: "John", age: 30, - "likes birds": true // multiword property name must be quoted + "likes birds": true // "likes birds" ("gosta de pássaros") - o nome de propriedade com múltiplas palavras tem de estar entre aspas }; ``` ![](object-user-props.svg) +A última propriedade da lista pode terminar com uma vírgula: -The last property in the list may end with a comma: ```js let user = { name: "John", age: 30*!*,*/!* } ``` -That is called a "trailing" or "hanging" comma. Makes it easier to add/remove/move around properties, because all lines become alike. -## Square brackets +Esta é chamada de vírgula à direita (*trailing comma*) ou "vírgula pendurada" (*hanging comma*). Ela facilita o adicionar/remover/mover propriedades, porque todas as linhas serão semelhantes (as propriedades são separadas por vírgulas). -For multiword properties, the dot access doesn't work: +## Parênteses retos + +Para propriedades com múltiplas palavras, o acesso por ponto não funciona: ```js run -// this would give a syntax error +// isto daria um erro de sintaxe user.likes birds = true ``` -That's because the dot requires the key to be a valid variable identifier. That is: no spaces and other limitations. +Isto, porque o ponto requere que a chave (*key*) seja um identificador de variável válido. Isto é: sem espaços e outras restrições. -There's an alternative "square bracket notation" that works with any string: +Existe uma alternativa, a "notação por parênteses retos", que funciona com qualquer *string* (cadeia-de-carateres): ```js run let user = {}; -// set +// cria user["likes birds"] = true; -// get -alert(user["likes birds"]); // true +// lê +alert(user["likes birds"]); // true ('verdadeiro') -// delete +// remove delete user["likes birds"]; ``` -Now everything is fine. Please note that the string inside the brackets is properly quoted (any type of quotes will do). +Agora, tudo está bem. Por favor, verifique se a *string* dentro dos parênteses retos está própriamente encerrada entre aspas (qualquer tipo de aspas serve). -Square brackets also provide a way to obtain the property name as the result of any expression -- as opposed to a literal string -- like from a variable as follows: +Os parênteses retos, também fornecem uma forma de se obter o nome de uma propriedade como resultado de uma expressão -- em vez de uma *string* literal -- como a partir de uma variável, a exemplo: ```js let key = "likes birds"; -// same as user["likes birds"] = true; +// o mesmo que 'user["likes birds"] = true;' user[key] = true; ``` -Here, the variable `key` may be calculated at run-time or depend on the user input. And then we use it to access the property. That gives us a great deal of flexibility. The dot notation cannot be used in a similar way. +Aqui, a variável `key` pode ser calculada em tempo de execução (*run-time*) ou depender de uma entrada pelo utilizador (*user input*). E depois a utilizamos para aceder à propriedade. Isso, dá-nos um grande grau de flexibilidade. -For instance: +Por exemplo: ```js run let user = { @@ -140,15 +141,13 @@ let user = { age: 30 }; -let key = prompt("What do you want to know about the user?", "name"); +let key = prompt("O que quer saber acerca do utilizador?", "name"); -// access by variable -alert( user[key] ); // John (if enter "name") +// aceda à variável +alert( user[key] ); // John (se a entrada tiver sido "name") ``` -<<<<<<< HEAD -======= -The dot notation cannot be used in a similar way: +A notação por ponto não pode ser usada de forma semelhante: ```js run let user = { @@ -159,42 +158,41 @@ let user = { let key = "name"; alert( user.key ) // undefined ``` ->>>>>>> 852ee189170d9022f67ab6d387aeae76810b5923 -### Computed properties +### Propriedades computadas -We can use square brackets in an object literal. That's called *computed properties*. +Podemos utilizar os parênteses retos num object literal. Chamam-se de *propriedades computadas*. -For instance: +Por exemplo: ```js run -let fruit = prompt("Which fruit to buy?", "apple"); +let fruit = prompt("Que fruta comprar?", "apple"); let bag = { *!* - [fruit]: 5, // the name of the property is taken from the variable fruit + [fruit]: 5, // o nome da propriedade é obtido por meio da variável 'fruit' */!* }; alert( bag.apple ); // 5 if fruit="apple" ``` -The meaning of a computed property is simple: `[fruit]` means that the property name should be taken from `fruit`. +O significado de uma propriedade computada é simples: `[fruit]` diz que o nome da propriedade é obtido por meio de `fruit`. -So, if a visitor enters `"apple"`, `bag` will become `{apple: 5}`. +Assim, se um visitante inserir `"apple"`, `bag` se tornará em `{apple: 5}`. -Essentially, that works the same as: +Essencialmente, isso é o mesmo que: ```js run -let fruit = prompt("Which fruit to buy?", "apple"); +let fruit = prompt("Que fruta comprar?", "apple"); let bag = {}; -// take property name from the fruit variable +// obtenha o nome da propriedade por meio da variável fruit bag[fruit] = 5; ``` -...But looks nicer. +...Mas, tem uma melhor apresentação. -We can use more complex expressions inside square brackets: +Podemos usar expressões mais complexas dentro dos parênteses retos: ```js let fruit = 'apple'; @@ -203,16 +201,14 @@ let bag = { }; ``` -Square brackets are much more powerful than the dot notation. They allow any property names and variables. But they are also more cumbersome to write. - -So most of the time, when property names are known and simple, the dot is used. And if we need something more complex, then we switch to square brackets. - +Parênteses retos, são mais poderosos que a notação por ponto. Eles permitem quaisquer nomes de propriedades e variáveis. Mas, eles também envolvem mais trabalho para escrever. +Assim, a maior parte as vezes, quando nomes de propriedades são conhecidos e simples, o ponto é utilizado. E, se precisarmos de algo mais complexo, mudamos para os parênteses retos. ````smart header="Reserved words are allowed as property names" -A variable cannot have a name equal to one of language-reserved words like "for", "let", "return" etc. +Uma variável, não pode ter um nome igual a uma das palavras reservadas ('keywords') da linguagem, como "for", "let", "return" etc. -But for an object property, there's no such restriction. Any name is fine: +Mas, para uma propriedade de um objeto, não existe tal restrição. Qualquer nome é aceitável: ```js run let obj = { @@ -224,28 +220,27 @@ let obj = { alert( obj.for + obj.let + obj.return ); // 6 ``` -Basically, any name is allowed, but there's a special one: `"__proto__"` that gets special treatment for historical reasons. For instance, we can't set it to a non-object value: +Basicamente, qualquer nome é permitido, mas existe um especial: `"__proto__"`, que tem um tratamento particular por razões históricas. Por exemplo, a ele não podemos atribuir um valor não-objeto: ```js run let obj = {}; obj.__proto__ = 5; -alert(obj.__proto__); // [object Object], didn't work as intended +alert(obj.__proto__); // [object Object], não resultou como esperado ``` -As we see from the code, the assignment to a primitive `5` is ignored. +Como vemos pelo código, a atribuição do primitivo `5` é ignorada. -That can become a source of bugs and even vulnerabilities if we intend to store arbitrary key-value pairs in an object, and allow a visitor to specify the keys. +Isso, pode se tornar numa fonte de erros ('bugs') e até de vulnerabilidades, se pretendermos armazenar pares chave-valor arbitrários num objeto, e permitir a um visitante especificar as chaves ('keys'). -In that case the visitor may choose "__proto__" as the key, and the assignment logic will be ruined (as shown above). +Nesse caso, o the visitante pode escolher "__proto__" como chave, e a lógica de atribuição estará arruinada (como se mostra acima). -There is a way to make objects treat `__proto__` as a regular property, which we'll cover later, but first we need to know more about objects. -There's also another data structure [Map](info:map-set-weakmap-weakset), that we'll learn in the chapter , which supports arbitrary keys. +Existe uma forma de fazer os objetos tratarem `__proto__` como uma propriedade regular, que analisaremos mais adiante, mas primeiro precisamos de saber mais sobre objetos. +Existe também outra estrutura de dados [Map](info:map-set-weakmap-weakset), que aprenderemos no capítulo , que suporta chaves arbitrárias. ```` +## Abreviação do valor da propriedade -## Property value shorthand - -In real code we often use existing variables as values for property names. +Em código real, frequentemente empregamos variáveis semelhantes a valores como nomes de propriedades. For instance: @@ -254,7 +249,7 @@ function makeUser(name, age) { return { name: name, age: age - // ...other properties + // ...outras propriedades }; } @@ -262,103 +257,102 @@ let user = makeUser("John", 30); alert(user.name); // John ``` -In the example above, properties have the same names as variables. The use-case of making a property from a variable is so common, that there's a special *property value shorthand* to make it shorter. +No exemplo acima, propriedades têm os mesmos nomes que as variáveis. O caso prático (*use-case*) de construir uma propriedade com base numa variável é tão comum, que existe uma especial *abreviação do valor da propriedade* (*property value shorthand*) para a tornar mais curta. -Instead of `name:name` we can just write `name`, like this: +Em vez de `name:name`, podemos simplesmente escrever `name`, como abaixo: ```js function makeUser(name, age) { *!* return { - name, // same as name: name - age // same as age: age + name, // o mesmo que name: name + age // o mesmo que age: age // ... }; */!* } ``` -We can use both normal properties and shorthands in the same object: +Podemos empregar ambas, as propriedades normais e as abreviações (*shorthands*) no mesmo objeto: ```js let user = { - name, // same as name:name + name, // o mesmo que name:name age: 30 }; ``` -## Existence check +## Verificação de existência -A notable objects feature is that it's possible to access any property. There will be no error if the property doesn't exist! Accessing a non-existing property just returns `undefined`. It provides a very common way to test whether the property exists -- to get it and compare vs undefined: +Uma particularidade notável de objetos, é que é possível aceder a qualquer propriedade. Não haverá erro se a propriedade não existir! Aceder a uma propriedade não-existente apenas retorna `undefined`. Ela, fornece uma forma muito comum de testar se a propriedade existe -- aceda, e compare o resultado com *undefined*: ```js run let user = {}; -alert( user.noSuchProperty === undefined ); // true means "no such property" +alert( user.noSuchProperty === undefined ); // true, significa "propriedade não existente" (no such property) ``` -There also exists a special operator `"in"` to check for the existence of a property. +Também existe um operador especial, `"in"`, para verificar a existência de uma propriedade. + +A sintaxe é: -The syntax is: ```js "key" in object ``` -For instance: +Por exemplo: ```js run let user = { name: "John", age: 30 }; -alert( "age" in user ); // true, user.age exists -alert( "blabla" in user ); // false, user.blabla doesn't exist +alert( "age" in user ); // true (verdadeiro), 'user.age' existe +alert( "blabla" in user ); // false (falso), 'user.blabla' não existe ``` -Please note that on the left side of `in` there must be a *property name*. That's usually a quoted string. +Por favor, note que no lado esquerdo de `in` deve existir um *nome de propriedade*. Geralmente, é uma *string* entre aspas. -If we omit quotes, that would mean a variable containing the actual name will be tested. For instance: +Se omitirmos as aspas, isso terá o significado de uma variável contendo o atual nome a ser testado. Por exemplo: ```js run let user = { age: 30 }; let key = "age"; -alert( *!*key*/!* in user ); // true, takes the name from key and checks for such property +alert( *!*key*/!* in user ); // true (verdadeiro), recebe o nome por meio de 'key' e procura por tal propriedade ``` -````smart header="Using \"in\" for properties that store `undefined`" -Usually, the strict comparison `"=== undefined"` check works fine. But there's a special case when it fails, but `"in"` works correctly. +````smart header="Using "in" for properties that store "undefined"" +Geralmente, a comparação exata ('strict') para a verificação `"=== undefined"` funciona bem. Mas, existe um caso especial em que falha. Contudo, `"in"` funciona corretamente. -It's when an object property exists, but stores `undefined`: +É quando uma propriedade de um objeto existe, mas possui `undefined` nela armazenado: ```js run let obj = { test: undefined }; -alert( obj.test ); // it's undefined, so - no such property? +alert( obj.test ); // exibe 'undefined', então - tal propriedade não existe? -alert( "test" in obj ); // true, the property does exist! +alert( "test" in obj ); // true (verdadeiro), a propriedade na realidade existe! ``` +No código acima, a propriedade `obj.test` tecnicamente existe. Deste modo, o operador `in` funciona corretamente. -In the code above, the property `obj.test` technically exists. So the `in` operator works right. - -Situations like this happen very rarely, because `undefined` is usually not assigned. We mostly use `null` for "unknown" or "empty" values. So the `in` operator is an exotic guest in the code. +Situações como esta muito raramente ocorrem, porque `undefined` não é usualmente atribuido. Em geral, empregamos `null` para valores "desconhecidos" ou "vazios". Deste modo, o operador `in` é um convidado exótico na codificação. ```` +## O laço "for..in" -## The "for..in" loop +Para navegar por todas as chaves (*keys*) de um objeto, existe uma forma especial de laço (*loop*): `for..in`. Esta, é uma construção completamente diferente da do `for(;;)`, que estudámos antes. -To walk over all keys of an object, there exists a special form of the loop: `for..in`. This is a completely different thing from the `for(;;)` construct that we studied before. - -The syntax: +A sintaxe: ```js for (key in object) { - // executes the body for each key among object properties + // executa o corpo do laço, por cada chave (key) de entre as propriedades do objeto } ``` -For instance, let's output all properties of `user`: +Por exemplo, vamos imprimir todas propriedades de `user`: ```js run let user = { @@ -368,33 +362,32 @@ let user = { }; for (let key in user) { - // keys - alert( key ); // name, age, isAdmin - // values for the keys + // key (chave) + alert( key ); // 'name', 'age', isAdmin' + // valor por chave (key) alert( user[key] ); // John, 30, true } ``` -Note that all "for" constructs allow us to declare the looping variable inside the loop, like `let key` here. - -Also, we could use another variable name here instead of `key`. For instance, `"for (let prop in obj)"` is also widely used. +Note, que todas as construções "for" permitem-nos declarar a variável do laço dentro do ciclo (*loop*), como `let key` aqui. +De igual modo, poderíamos usar aqui um nome de variável differente de `key`. Por exemplo, `"for (let prop in obj)"` também é largamente utilizado. -### Ordered like an object +### Ordenado como um objeto -Are objects ordered? In other words, if we loop over an object, do we get all properties in the same order they were added? Can we rely on this? +Os objetos são ordenados? Por outras palavras, se percorrermos um objeto com um laço, será que obtemos todas as propriedades pela mesma ordem em que foram adicionadas? Poderemos confiar nisso? -The short answer is: "ordered in a special fashion": integer properties are sorted, others appear in creation order. The details follow. +A curta resposta é: "ordenados de um modo especial" - propriedades inteiras são ordenadas de forma crescente, outras aparecem na ordem em que foram criadas. Detalhes a seguir. -As an example, let's consider an object with the phone codes: +Como exemplo, considermos um objeto com indicativos telefónicos de países: ```js run let codes = { - "49": "Germany", - "41": "Switzerland", - "44": "Great Britain", + "49": "Alemanha", + "41": "Suíça", + "44": "Grã Bretanha", // .., - "1": "USA" + "1": "EUA" }; *!* @@ -404,56 +397,59 @@ for (let code in codes) { */!* ``` -The object may be used to suggest a list of options to the user. If we're making a site mainly for German audience then we probably want `49` to be the first. +O objeto, pode ser empregue como sugestão de uma lista de opções para o utilizador. Se, estivermos a construir um *site* maioritariamente para uma audiência Alemã, então provavelmente queremos `49` como o primeiro. -But if we run the code, we see a totally different picture: +Mas, ao correr o código, vemos uma imagem totalmente diferente: -- USA (1) goes first -- then Switzerland (41) and so on. +- EUA (1) vem em primeiro lugar, +- depois a Suiça (41), e assim por adiante. -The phone codes go in the ascending sorted order, because they are integers. So we see `1, 41, 44, 49`. +Os indicativos telefónicos, são ordenados por ordem ascendente, porque são inteiros. Por isso, vemos `1, 41, 44, 49`. ````smart header="Integer properties? What's that?" -The "integer property" term here means a string that can be converted to-and-from an integer without a change. +O termo "propriedade inteira" aqui, significa que uma *string* pode ser convertida para inteiro ('integer') e, de volta reconvertida sem qualquer alteração. -So, "49" is an integer property name, because when it's transformed to an integer number and back, it's still the same. But "+49" and "1.2" are not: +Assim, "49" é um nome de propriedade inteiro porque, ao ser transformado num número inteiro e de volta reconvertido, continua o mesmo. Mas, "+49" e "1.2" não são: ```js run -// Math.trunc is a built-in function that removes the decimal part -alert( String(Math.trunc(Number("49"))) ); // "49", same, integer property -alert( String(Math.trunc(Number("+49"))) ); // "49", not same "+49" ⇒ not integer property -alert( String(Math.trunc(Number("1.2"))) ); // "1", not same "1.2" ⇒ not integer property +// Math.trunc é uma função incorporada (*built-in function*) que remove a parte decimal + +alert( String(Math.trunc(Number("49"))) ); // "49", inalterado ⇒ propriedade inteira + +alert( String(Math.trunc(Number("+49"))) ); // "49", não o mesmo que "+49" ⇒ não é uma propriedade inteira + +alert( String(Math.trunc(Number("1.2"))) ); // "1", não o mesmo que "1.2" ⇒ não é uma propriedade inteira ``` ```` -...On the other hand, if the keys are non-integer, then they are listed in the creation order, for instance: +...Por outro lado, se as chaves (*keys*) forem não-inteiras, elas são listadas segundo a ordem em que foram criadas, por exemplo: ```js run let user = { name: "John", surname: "Smith" }; -user.age = 25; // add one more +user.age = 25; // adicione mais uma propriedade *!* -// non-integer properties are listed in the creation order +// propriedades não-inteiras são listadas segundo a ordem em que foram criadas */!* for (let prop in user) { - alert( prop ); // name, surname, age + alert( prop ); // 'name', 'surname', 'age' } ``` -So, to fix the issue with the phone codes, we can "cheat" by making the codes non-integer. Adding a plus `"+"` sign before each code is enough. +Portanto, para corrigir o problema dos indicativos telefónicos, podemos "aldrabar" tornando-os não-inteiros. Adicionar um sinal de mais `"+"`, antes de cada código é o suficiente. -Like this: +Desta forma: ```js run let codes = { - "+49": "Germany", - "+41": "Switzerland", - "+44": "Great Britain", + "+49": "Alemanha", + "+41": "Suiça", + "+44": "Grã Bretanha", // .., - "+1": "USA" + "+1": "EUA" }; for (let code in codes) { @@ -461,30 +457,30 @@ for (let code in codes) { } ``` -Now it works as intended. +Agora, funciona como pretendido. -## Copying by reference +## Cópia por referência -One of the fundamental differences of objects vs primitives is that they are stored and copied "by reference". +Uma das principais diferenças entre objetos vs primitivos, está em que os primeiros são armazenados e copiados "por referência" (*by reference*). -Primitive values: strings, numbers, booleans -- are assigned/copied "as a whole value". +Valores primitivos: *strings*, números, booleanos -- são atribuidos/copiados como "o próprio valor". -For instance: +Por exemplo: ```js let message = "Hello!"; let phrase = message; ``` -As a result we have two independent variables, each one is storing the string `"Hello!"`. +Como resultado, temos duas variáveis independentes, mas cada uma armazenando a *string* (cadeia-de-carateres) `"Hello!"`. ![](variable-copy-value.svg) -Objects are not like that. +Objetos não são assim. -**A variable stores not the object itself, but its "address in memory", in other words "a reference" to it.** +**Uma variável não armazena o próprio objeto, mas o seu "endereço em memória" (*address in memory*), por outras palavras "uma referência" (*reference*) a ele.** -Here's the picture for the object: +Aqui, está a imagem para o objeto: ```js let user = { @@ -494,25 +490,25 @@ let user = { ![](variable-contains-reference.svg) -Here, the object is stored somewhere in memory. And the variable `user` has a "reference" to it. +Aqui, o objeto é armazenado algures na memória. E a variável `user` contém uma "referência" para ele. -**When an object variable is copied -- the reference is copied, the object is not duplicated.** +**Quando uma variável com um objeto é copiada -- é a referência copiada, o objeto não é duplicado.** -If we imagine an object as a cabinet, then a variable is a key to it. Copying a variable duplicates the key, but not the cabinet itself. +Se imaginarmos um objeto como um fichário, então uma variável será uma chave (*a key*) para ele. Copiando uma variável duplica a chave (*the key*), não o próprio fichário. -For instance: +Por exemplo: ```js no-beautify let user = { name: "John" }; -let admin = user; // copy the reference +let admin = user; // copia a referência ``` -Now we have two variables, each one with the reference to the same object: +Agora, temos duas variáveis, e cada uma com a referência para o mesmo objeto: ![](variable-copy-reference.svg) -We can use any variable to access the cabinet and modify its contents: +Podemos utilizar qualquer das variáveis, para aceder ao fichário e alterar o seu conteúdo: ```js run let user = { name: 'John' }; @@ -520,46 +516,46 @@ let user = { name: 'John' }; let admin = user; *!* -admin.name = 'Pete'; // changed by the "admin" reference +admin.name = 'Pete'; // alterado através da referência em "admin" */!* -alert(*!*user.name*/!*); // 'Pete', changes are seen from the "user" reference +alert(*!*user.name*/!*); // 'Pete', as alterações também são visíveis por meio da referência em "user" ``` -The example above demonstrates that there is only one object. As if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use the other key (`user`) we would see changes. +O exemplo acima, demonstra que apenas existe um objecto. Como se tivéssemos um fichário com duas chaves, e usássemos uma delas (`admin`) para o aceder. E depois, se mais tarde usássemos a outra chave (`user`) poderíamos ver as alterações. -### Comparison by reference +### Comparação por referência -The equality `==` and strict equality `===` operators for objects work exactly the same. +Os operadores de igualdade `==` e de igualdade exata (*strict*) `===` para objetos funcionam exatamente da mesma forma. -**Two objects are equal only if they are the same object.** +**Dois objetos apenas são iguais se eles forem o mesmo objeto.** -For instance, two variables reference the same object, they are equal: +Por exemplo, duas variáveis referenciam o mesmo objeto, elas são iguais: ```js run let a = {}; -let b = a; // copy the reference +let b = a; // cópia por referência -alert( a == b ); // true, both variables reference the same object -alert( a === b ); // true +alert( a == b ); // true (verdadeiro), ambas as variáveis referenciam o mesmo objeto +alert( a === b ); // true (verdadeiro) ``` -And here two independent objects are not equal, even though both are empty: +E aqui, dois objetos independentes não são iguais, muito embora ambos sejam vazios: ```js run let a = {}; -let b = {}; // two independent objects +let b = {}; // dois objetos independentes -alert( a == b ); // false +alert( a == b ); // false (falso) ``` -For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj == 5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons are necessary very rarely and usually are a result of a coding mistake. +Para comparações como `obj1 > obj2` ou para uma comparação com um primitivo `obj == 5`, objetos são convertidos para primitivos. Estudaremos como funciona a conversão de objetos muito em breve, mas para dizer a verdade, tais comparações são muito raramente necessárias e são geralmente o resultado de um erro de código. -### Const object +### Objeto constante -An object declared as `const` *can* be changed. +Um objeto declarado com `const` *pode* ser alterado. -For instance: +Por exemplo: ```js run const user = { @@ -573,9 +569,9 @@ user.age = 25; // (*) alert(user.age); // 25 ``` -It might seem that the line `(*)` would cause an error, but no, there's totally no problem. That's because `const` fixes the value of `user` itself. And here `user` stores the reference to the same object all the time. The line `(*)` goes *inside* the object, it doesn't reassign `user`. +Parece que a linha `(*)` irá causar um erro, mas não, não há totalmente qualquer problema. Isso, porque `const` apenas fixa o valor de `user`. Então, aqui `user` armazena uma referência para um mesmo objeto pelo tempo todo. A linha `(*)` vai para *dentro* do objeto, não faz uma re-atribuição a `user`. -The `const` would give an error if we try to set `user` to something else, for instance: +A `const` produzirá um erro se tentarmos colocar em `user` qualquer outra coisa, por exemplo: ```js run const user = { @@ -583,26 +579,26 @@ const user = { }; *!* -// Error (can't reassign user) +// Erro (não é possível reatribuir a 'user') */!* user = { name: "Pete" }; ``` -...But what if we want to make constant object properties? So that `user.age = 25` would give an error. That's possible too. We'll cover it in the chapter . +...Mas, se quisermos tornar as propriedades do objeto constantes? Então, aí `user.age = 25` produzirá um erro. Isso, também é possível. Iremos cobrir isto no capítulo . -## Cloning and merging, Object.assign +## Clonar e fundir, Object.assign -So, copying an object variable creates one more reference to the same object. +Portanto, a cópia de uma variável de objeto cria mais uma referência para o mesmo objeto. -But what if we need to duplicate an object? Create an independent copy, a clone? +Mas, se quisermos duplicar um objecto? Criar uma cópia independente, um *clone*? -That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. Actually, that's rarely needed. Copying by reference is good most of the time. +Também se pode fazer, mas é um pouco mais difícil, porque não existe método incorporado (*built-in*) ao JavaScript para isso. Na verdade, isso raramente é necessário. A cópia por referência é a maior parte das vezes boa. -But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level. +Mas, se realmente quisermos isto, aí precisaremos de criar um novo objeto e replicar a estrutura do existente iterando pelas suas propriedades e copiando-as, digamos num nível primitivo. -Like this: +Desta forma: ```js run let user = { @@ -611,32 +607,32 @@ let user = { }; *!* -let clone = {}; // the new empty object +let clone = {}; // o novo objeto vazio -// let's copy all user properties into it +// copiemos todas as propriedades de 'user' para aquele for (let key in user) { clone[key] = user[key]; } */!* -// now clone is a fully independent clone -clone.name = "Pete"; // changed the data in it +// agora,'clone' é um clone completamente independente +clone.name = "Pete"; // altere dados nele -alert( user.name ); // still John in the original object +alert( user.name ); // contudo, ainda está 'John' no objeto original ``` -Also we can use the method [Object.assign](mdn:js/Object/assign) for that. +Podemos também empregar o método [Object.assign](mdn:js/Object/assign) para isso. -The syntax is: +A sintaxe é: ```js Object.assign(dest, [src1, src2, src3...]) ``` -- Arguments `dest`, and `src1, ..., srcN` (can be as many as needed) are objects. -- It copies the properties of all objects `src1, ..., srcN` into `dest`. In other words, properties of all arguments starting from the 2nd are copied into the 1st. Then it returns `dest`. +- Os argumentos `dest`, e `src1, ..., srcN` (que podem ser tantos quantos necessários) são objetos. +- Ele copia as propriedades de todos os objects `src1, ..., srcN` para `dest`. Por outras palavras, propriedades de todos os objetos, a começar pelo segundo, são copiadas para o primeiro. Depois, ele retorna `dest`. -For instance, we can use it to merge several objects into one: +Por exemplo, podemos utilizá-lo para fundir vários objetos num só: ```js let user = { name: "John" }; @@ -644,25 +640,25 @@ let permissions1 = { canView: true }; let permissions2 = { canEdit: true }; *!* -// copies all properties from permissions1 and permissions2 into user +// copia todas propriedades de 'permissions1' e 'permissions2' para 'user' Object.assign(user, permissions1, permissions2); */!* -// now user = { name: "John", canView: true, canEdit: true } +// agora, user = { name: "John", canView: true, canEdit: true } ``` -If the receiving object (`user`) already has the same named property, it will be overwritten: +Se, o objeto recetor (`user`) já tiver alguma propriedade com o mesmo nome, ela será substituída (*overwritten*): ```js let user = { name: "John" }; -// overwrite name, add isAdmin +// substitua ('overwrite') 'nome', e adicione 'isAdmin' Object.assign(user, { name: "Pete", isAdmin: true }); -// now user = { name: "Pete", isAdmin: true } +// agora, user = { name: "Pete", isAdmin: true } ``` -We also can use `Object.assign` to replace the loop for simple cloning: +Podemos também utilizar `Object.assign` para substituir o ciclo (*loop*) acima para uma clonagem simples: ```js let user = { @@ -675,11 +671,12 @@ let clone = Object.assign({}, user); */!* ``` -It copies all properties of `user` into the empty object and returns it. Actually, the same as the loop, but shorter. +Ele copia todas as propriedades de `user` para o objecto vazio e retorna este. Na verdade, é o mesmo laço (*loop*), mas mais curto. + +Até agora, assumimos que todas as propriedades de `user` são primitivas. Mas, propriedades podem ser referências para outros objetos. O que fazer nesse caso? -Until now we assumed that all properties of `user` are primitive. But properties can be references to other objects. What to do with them? +Como aqui: -Like this: ```js run let user = { name: "John", @@ -692,9 +689,10 @@ let user = { alert( user.sizes.height ); // 182 ``` -Now it's not enough to copy `clone.sizes = user.sizes`, because the `user.sizes` is an object, it will be copied by reference. So `clone` and `user` will share the same sizes: +Agora, não é suficiente efetuar a cópia `clone.sizes = user.sizes`, porque `user.sizes` é um objeto, e aí seria copiado por referência. Então, `clone` e `user` iriam partilhar a mesma propriedade "*sizes*": + +Deste modo: -Like this: ```js run let user = { name: "John", @@ -706,49 +704,48 @@ let user = { let clone = Object.assign({}, user); -alert( user.sizes === clone.sizes ); // true, same object +alert( user.sizes === clone.sizes ); // true (verdadeiro), é o mesmo objeto -// user and clone share sizes -user.sizes.width++; // change a property from one place -alert(clone.sizes.width); // 51, see the result from the other one +// 'user' e 'clone' partilham 'sizes' +user.sizes.width++; // altere uma propriedade num lugar +alert(clone.sizes.width); // 51, e verá o resultado a partir do outro ``` -To fix that, we should use the cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning". - -There's a standard algorithm for deep cloning that handles the case above and more complex cases, called the [Structured cloning algorithm](http://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data). In order not to reinvent the wheel, we can use a working implementation of it from the JavaScript library [lodash](https://lodash.com), the method is called [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). - +Para corrigir isso, deveriamos empregar o laço (*loop*) para clonagem, que examina cada valor de `user[key]` e, se for um objeto, então também replica essa estrutura. Essa, é chamada de uma "clonagem profunda" ("*deep cloning*"). +Existe um algoritmo padrão (*standard*) para clonagem profunda (deep cloning), que trata tanto do caso acima como de mais complexos, chamado de [Structured cloning algorithm](http://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data) (algoritmo de clonagem de estruturas). Para não se reinventar a roda, poderemos utilizar uma implementação operacional do mesmo disponível na biblioteca (*library*) de JavaScript [lodash](https://lodash.com), o método é chamado [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). -## Summary +## Sumário -Objects are associative arrays with several special features. +Objetos são *arrays* associativos (*associative arrays*), com várias funcionalidades especiais. -They store properties (key-value pairs), where: -- Property keys must be strings or symbols (usually strings). -- Values can be of any type. +Eles armazenam propriedades em pares chave-valor, onde: +- As chaves das propriedades devem ser *strings* ou símbolos (geralmente *strings*). +- Valores podem ser de qualquer tipo. -To access a property, we can use: -- The dot notation: `obj.property`. -- Square brackets notation `obj["property"]`. Square brackets allow to take the key from a variable, like `obj[varWithKey]`. +Para aceder a uma propriedade, podemos utilizar: +- A notação por ponto: `obj.property`. +- A notação por parênteses retos `obj["property"]`. Os parênteses retos permitem receber a chave de uma variável, como por exemplo `obj[varWithKey]`. -Additional operators: -- To delete a property: `delete obj.prop`. -- To check if a property with the given key exists: `"key" in obj`. -- To iterate over an object: `for (let key in obj)` loop. +Operadores adicionais: +- Para remover uma propriedade: `delete obj.prop`. +- Para verificar se uma propriedade com uma dada chave existe: `"key" in obj`. +- Para iterar sobre um objeto: o ciclo `for (let key in obj)`. -Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object. All operations via copied references (like adding/removing properties) are performed on the same single object. +Objetos são atribuidos e copiados por referência. Por outras palavras, uma variável não armazena o "valor do objeto", mas uma "referência" (endereço em memória) do valor. Assim, copiar tal variável ou passá-la como argumento de uma função copia tal referência, não o objeto. Todas as operações sobre cópias de referências (como adicionar/remover propriedades) são executadas sobre um mesmo único objeto. -To make a "real copy" (a clone) we can use `Object.assign` or [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). + Para efetuar uma "verdadeira cópia" (um clone), podemos utilizar `Object.assign` ou [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). -What we've studied in this chapter is called a "plain object", or just `Object`. +O que estudámos neste capítulo é o chamado "objeto simples" ("*plain object*"), ou simplesmente `Objeto`. -There are many other kinds of objects in JavaScript: +Existem muitos outros tipos de objetos em JavaScript: -- `Array` to store ordered data collections, -- `Date` to store the information about the date and time, -- `Error` to store the information about an error. -- ...And so on. +- `Array` para armazenar coleções de dados ordenadas, +- `Date` para armazenar informação sobre data e tempo, +- `Error` para armazenar informação sobre um erro. +- ...E outros mais. -They have their special features that we'll study later. Sometimes people say something like "Array type" or "Date type", but formally they are not types of their own, but belong to a single "object" data type. And they extend it in various ways. +Eles têm as suas funcionalidades especiais, que estudaremos mais adiante. Por vezes, pessoas dizem algo como "o tipo +Array" ou "o tipo Data" (*Date*), mas formalmente eles não são própriamente tipos, mas pertencem a um único tipo de dados "objeto". E o extendem de várias formas. -Objects in JavaScript are very powerful. Here we've just scratched the surface of a topic that is really huge. We'll be closely working with objects and learning more about them in further parts of the tutorial. +Objetos em JavaScript são muito poderosos. Aqui, apenas tocámos na superfície de um realmente amplo tópico. Iremos, mais especificamente, trabalhar e aprender sobre objetos em futuras partes do tutorial. diff --git a/1-js/04-object-basics/index.md b/1-js/04-object-basics/index.md index d2387aafa..991117d25 100644 --- a/1-js/04-object-basics/index.md +++ b/1-js/04-object-basics/index.md @@ -1 +1 @@ -# Objects: the basics +# Objetos: o básico From e788cff1378d6dcecdfd267c879df2efc0b85d68 Mon Sep 17 00:00:00 2001 From: odsantos Date: Tue, 22 Oct 2019 06:28:04 +0100 Subject: [PATCH 2/3] Revert "translate '01-object' directory files" This reverts commit f3fb7d2927a16e702ac7683957ff2981c86d31c5. --- .../01-object/2-hello-object/solution.md | 2 + .../01-object/2-hello-object/task.md | 14 +- .../01-object/3-is-empty/_js.view/solution.js | 2 +- .../01-object/3-is-empty/_js.view/test.js | 4 +- .../01-object/3-is-empty/solution.md | 2 +- .../01-object/3-is-empty/task.md | 13 +- .../01-object/4-const-object/solution.md | 10 +- .../01-object/4-const-object/task.md | 6 +- .../01-object/5-sum-object/task.md | 8 +- .../8-multiply-numeric/_js.view/source.js | 6 +- .../8-multiply-numeric/_js.view/test.js | 8 +- .../01-object/8-multiply-numeric/task.md | 20 +- 1-js/04-object-basics/01-object/article.md | 473 +++++++++--------- 1-js/04-object-basics/index.md | 2 +- 14 files changed, 289 insertions(+), 281 deletions(-) diff --git a/1-js/04-object-basics/01-object/2-hello-object/solution.md b/1-js/04-object-basics/01-object/2-hello-object/solution.md index dff006076..60083b963 100644 --- a/1-js/04-object-basics/01-object/2-hello-object/solution.md +++ b/1-js/04-object-basics/01-object/2-hello-object/solution.md @@ -1,4 +1,5 @@ + ```js let user = {}; user.name = "John"; @@ -6,3 +7,4 @@ user.surname = "Smith"; user.name = "Pete"; delete user.name; ``` + diff --git a/1-js/04-object-basics/01-object/2-hello-object/task.md b/1-js/04-object-basics/01-object/2-hello-object/task.md index c0e296444..2841a058f 100644 --- a/1-js/04-object-basics/01-object/2-hello-object/task.md +++ b/1-js/04-object-basics/01-object/2-hello-object/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Olá, objeto +# Hello, object -Escreva o código, uma ação por linha: +Write the code, one line for each action: -1. Crie um objeto vazio (*empty object*) `user`. -2. Adicione a propriedade `name` com o valor `John`. -3. Adicione a propriedade `surname` com o valor `Smith`. -4. Altere o valor de `name` para `Pete`. -5. Remova a propriedade `name` do objeto. +1. Create an empty object `user`. +2. Add the property `name` with the value `John`. +3. Add the property `surname` with the value `Smith`. +4. Change the value of the `name` to `Pete`. +5. Remove the property `name` from the object. diff --git a/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js b/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js index ca7dc324e..db3283e49 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js +++ b/1-js/04-object-basics/01-object/3-is-empty/_js.view/solution.js @@ -1,6 +1,6 @@ function isEmpty(obj) { for (let key in obj) { - // se o laço começou, existe uma propriedade + // if the loop has started, there is a property return false; } return true; diff --git a/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js b/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js index 400577698..4db5efabe 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js +++ b/1-js/04-object-basics/01-object/3-is-empty/_js.view/test.js @@ -1,9 +1,9 @@ describe("isEmpty", function() { - it("retorna verdadeiro para um objeto vazio", function() { + it("returns true for an empty object", function() { assert.isTrue(isEmpty({})); }); - it("retorna falso se uma propriedade existir", function() { + it("returns false if a property exists", function() { assert.isFalse(isEmpty({ anything: false })); diff --git a/1-js/04-object-basics/01-object/3-is-empty/solution.md b/1-js/04-object-basics/01-object/3-is-empty/solution.md index 6c328fc39..b876973b5 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/solution.md +++ b/1-js/04-object-basics/01-object/3-is-empty/solution.md @@ -1 +1 @@ -Simplemente, percorra (*loop over*) o objeto e imediatamente `return false` se pelo menos houver uma propriedade. +Just loop over the object and `return false` immediately if there's at least one property. diff --git a/1-js/04-object-basics/01-object/3-is-empty/task.md b/1-js/04-object-basics/01-object/3-is-empty/task.md index a499e6eb7..c438d36a2 100644 --- a/1-js/04-object-basics/01-object/3-is-empty/task.md +++ b/1-js/04-object-basics/01-object/3-is-empty/task.md @@ -2,18 +2,19 @@ importance: 5 --- -# Verifique por vazio (*emptiness*) +# Check for emptiness -Escreva a função `isEmpty(obj)`, que retorna `true` se o objeto não tiver propriedades, e `false` caso contrário. +Write the function `isEmpty(obj)` which returns `true` if the object has no properties, `false` otherwise. + +Should work like that: -Deve assim funcionar: ```js let schedule = {}; -alert( isEmpty(schedule) ); // verdadeiro +alert( isEmpty(schedule) ); // true -schedule["8:30"] = "levante-se"; +schedule["8:30"] = "get up"; -alert( isEmpty(schedule) ); // falso +alert( isEmpty(schedule) ); // false ``` diff --git a/1-js/04-object-basics/01-object/4-const-object/solution.md b/1-js/04-object-basics/01-object/4-const-object/solution.md index 9cb150373..f73c2f92b 100644 --- a/1-js/04-object-basics/01-object/4-const-object/solution.md +++ b/1-js/04-object-basics/01-object/4-const-object/solution.md @@ -1,8 +1,8 @@ -Com certeza, funciona, sem problemas. +Sure, it works, no problem. -A `const` apenas protege a própria variável contra alterações. +The `const` only protects the variable itself from changing. -Por outras palavras, `user` armazena uma referência ao objeto. E não pode ser alterada. Mas, o conteúdo do objeto pode. +In other words, `user` stores a reference to the object. And it can't be changed. But the content of the object can. ```js run const user = { @@ -10,10 +10,10 @@ const user = { }; *!* -// funciona +// works user.name = "Pete"; */!* -// erro +// error user = 123; ``` diff --git a/1-js/04-object-basics/01-object/4-const-object/task.md b/1-js/04-object-basics/01-object/4-const-object/task.md index a0a1709dc..a9aada631 100644 --- a/1-js/04-object-basics/01-object/4-const-object/task.md +++ b/1-js/04-object-basics/01-object/4-const-object/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Objetos constantes? +# Constant objects? -É possível alterar um objeto declarado com `const`? O que acha? +Is it possible to change an object declared with `const`? What do you think? ```js const user = { @@ -12,7 +12,7 @@ const user = { }; *!* -// isto funciona? +// does it work? user.name = "Pete"; */!* ``` diff --git a/1-js/04-object-basics/01-object/5-sum-object/task.md b/1-js/04-object-basics/01-object/5-sum-object/task.md index b0caee202..7e3e048d0 100644 --- a/1-js/04-object-basics/01-object/5-sum-object/task.md +++ b/1-js/04-object-basics/01-object/5-sum-object/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Soma das propriedades de um objeto +# Sum object properties -Temos um objeto armazenando salários da nossa equipa: +We have an object storing salaries of our team: ```js let salaries = { @@ -14,6 +14,6 @@ let salaries = { } ``` -Escreva o código para somar todos os salários e armazenar na variável `sum`. Para o exemplo acima, deverá ser `390`. +Write the code to sum all salaries and store in the variable `sum`. Should be `390` in the example above. -Se `salaries` for vazio, então o resultado deve ser `0`. \ No newline at end of file +If `salaries` is empty, then the result must be `0`. \ No newline at end of file diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js index f2ffe4901..a02b1e1cb 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/source.js @@ -1,17 +1,17 @@ let menu = { width: 200, height: 300, - title: "O meu menu" + title: "My menu" }; function multiplyNumeric(obj) { - /* o seu código */ + /* your code */ } multiplyNumeric(menu); -alert( "largura do menu=" + menu.width + " altura=" + menu.height + " título=" + menu.title ); +alert( "menu width=" + menu.width + " height=" + menu.height + " title=" + menu.title ); diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js index 2ba28f769..064e5414f 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/_js.view/test.js @@ -1,17 +1,17 @@ describe("multiplyNumeric", function() { - it("multiplica todas as propriedades numéricas por 2", function() { + it("multiplies all numeric properties by 2", function() { let menu = { width: 200, height: 300, - title: "O meu menu" + title: "My menu" }; let result = multiplyNumeric(menu); assert.equal(menu.width, 400); assert.equal(menu.height, 600); - assert.equal(menu.title, "O meu menu"); + assert.equal(menu.title, "My menu"); }); - it("não retorna nada", function() { + it("returns nothing", function() { assert.isUndefined( multiplyNumeric({}) ); }); diff --git a/1-js/04-object-basics/01-object/8-multiply-numeric/task.md b/1-js/04-object-basics/01-object/8-multiply-numeric/task.md index 54fa7fceb..33eb89220 100644 --- a/1-js/04-object-basics/01-object/8-multiply-numeric/task.md +++ b/1-js/04-object-basics/01-object/8-multiply-numeric/task.md @@ -2,30 +2,32 @@ importance: 3 --- -# Multiplica as propriedades numéricas por 2 +# Multiply numeric properties by 2 -Crie uma função `multiplyNumeric(obj)` que multiplica todas as proriedades numéricas de `obj` por `2`. +Create a function `multiplyNumeric(obj)` that multiplies all numeric properties of `obj` by `2`. -Por exemplo: +For instance: ```js -// antes da chamada +// before the call let menu = { width: 200, height: 300, - title: "O meu menu" + title: "My menu" }; multiplyNumeric(menu); -// depois da chamada +// after the call menu = { width: 400, height: 600, - title: "O meu menu" + title: "My menu" }; ``` -Por favor, note que `multiplyNumeric` não precisa de retornar nada. Deve modificar o próprio objecto. +Please note that `multiplyNumeric` does not need to return anything. It should modify the object in-place. + +P.S. Use `typeof` to check for a number here. + -P.S. Use `typeof` para verificar por um número aqui. diff --git a/1-js/04-object-basics/01-object/article.md b/1-js/04-object-basics/01-object/article.md index baba98e3a..00706750c 100644 --- a/1-js/04-object-basics/01-object/article.md +++ b/1-js/04-object-basics/01-object/article.md @@ -1,60 +1,60 @@ -# Objetos +# Objects -Como sabemos, pelo capítulo , existem sete tipos de dados em JavaScript. Seis deles são chamados de "primitivos", porque os seus valores apenas contêm uma única coisa (seja ela uma cadeia-de-carateres [*string*], um número, ou o que for). +As we know from the chapter , there are seven data types in JavaScript. Six of them are called "primitive", because their values contain only a single thing (be it a string or a number or whatever). -Em contraste, objetos são empregues para armazenar por meio de uma chave, coleções de vários dados e entidades mais complexas. Em JavaScript, objetos penetram em quase todos os aspetos da linguagem. Portanto, devemos primeiro compreendê-los antes de nos envolvermos detalhadamente em algo mais. +In contrast, objects are used to store keyed collections of various data and more complex entities. In JavaScript, objects penetrate almost every aspect of the language. So we must understand them first before going in-depth anywhere else. -Um objeto pode ser criado por chavetas `{…}`, com uma lista opcional de *propriedades*. Uma propriedade é um par "key: value" (chave: valor), onde `key` é uma *string* (também chamada de "nome da propriedade"), e `value` pode ser qualquer coisa. +An object can be created with figure brackets `{…}` with an optional list of *properties*. A property is a "key: value" pair, where `key` is a string (also called a "property name"), and `value` can be anything. -Podemos imaginar um objeto como um fichário com ficheiros assinados. Cada peça de informação, é armazenada no seu ficheiro ligada a uma chave. É fácil encontrar um ficheiro através do seu nome, ou adicionar/remover um ficheiro. +We can imagine an object as a cabinet with signed files. Every piece of data is stored in its file by the key. It's easy to find a file by its name or add/remove a file. ![](object.svg) -Um objeto vazio ("fichário vazio"), pode ser criado por uma de duas sintaxes: +An empty object ("empty cabinet") can be created using one of two syntaxes: ```js -let user = new Object(); // sintaxe de "construtor de objetos" -let user = {}; // sintaxe de "objeto literal" +let user = new Object(); // "object constructor" syntax +let user = {}; // "object literal" syntax ``` ![](object-user-empty.svg) -Geralmente, são utilizadas as chavetas `{...}`. Essa declaração é chamada de *objeto literal*. +Usually, the figure brackets `{...}` are used. That declaration is called an *object literal*. -## Literais e propriedades +## Literals and properties -Podemos imediatamente colocar algumas propriedades dentro das `{...}` como pares "chave: valor" (*key: value*): +We can immediately put some properties into `{...}` as "key: value" pairs: ```js -let user = { // um objeto - name: "John", // na chave "name" armazene o valor "John" - age: 30 // na chave "age" armazene o valor 30 +let user = { // an object + name: "John", // by key "name" store value "John" + age: 30 // by key "age" store value 30 }; ``` -Uma propriedade, tem uma chave (*key* - também conhecida por "nome" ou "identificador") antes dos dois-pontos `":"` e um valor à sua direita. +A property has a key (also known as "name" or "identifier") before the colon `":"` and a value to the right of it. -No objeto `user`, existem duas propriedades: +In the `user` object, there are two properties: -1. A primeira, tem o nome `"name"` e o valor `"John"`. -2. A segunda, tem o nome `"age"` e o valor `30`. +1. The first property has the name `"name"` and the value `"John"`. +2. The second one has the name `"age"` and the value `30`. -O objeto `user` resultante, pode ser imaginado como um fichário com dois ficheiros assinados com as etiquetas "*name*" e "*age*". +The resulting `user` object can be imagined as a cabinet with two signed files labeled "name" and "age". ![user object](object-user.svg) -Podemos adicionar, remover e ler ficheiros dele a qualquer altura. +We can add, remove and read files from it any time. -Valores de propriedades podem ser acedidos usando a notação por ponto (*dot notation*): +Property values are accessible using the dot notation: ```js -// obtenha os campos do objeto: +// get fields of the object: alert( user.name ); // John alert( user.age ); // 30 ``` -O valor pode ser de qualquer tipo. Vamos adicionar um booleano: +The value can be of any type. Let's add a boolean one: ```js user.isAdmin = true; @@ -62,7 +62,7 @@ user.isAdmin = true; ![user object 2](object-user-isadmin.svg) -Para remover uma propriedade, podemos usar o operador `delete`: +To remove a property, we can use `delete` operator: ```js delete user.age; @@ -70,70 +70,69 @@ delete user.age; ![user object 3](object-user-delete.svg) -Podemos também usar nomes de propriedades com múltiplas palavras, mas aí eles têm de estar entre aspas: +We can also use multiword property names, but then they must be quoted: ```js let user = { name: "John", age: 30, - "likes birds": true // "likes birds" ("gosta de pássaros") - o nome de propriedade com múltiplas palavras tem de estar entre aspas + "likes birds": true // multiword property name must be quoted }; ``` ![](object-user-props.svg) -A última propriedade da lista pode terminar com uma vírgula: +The last property in the list may end with a comma: ```js let user = { name: "John", age: 30*!*,*/!* } ``` +That is called a "trailing" or "hanging" comma. Makes it easier to add/remove/move around properties, because all lines become alike. -Esta é chamada de vírgula à direita (*trailing comma*) ou "vírgula pendurada" (*hanging comma*). Ela facilita o adicionar/remover/mover propriedades, porque todas as linhas serão semelhantes (as propriedades são separadas por vírgulas). +## Square brackets -## Parênteses retos - -Para propriedades com múltiplas palavras, o acesso por ponto não funciona: +For multiword properties, the dot access doesn't work: ```js run -// isto daria um erro de sintaxe +// this would give a syntax error user.likes birds = true ``` -Isto, porque o ponto requere que a chave (*key*) seja um identificador de variável válido. Isto é: sem espaços e outras restrições. +That's because the dot requires the key to be a valid variable identifier. That is: no spaces and other limitations. -Existe uma alternativa, a "notação por parênteses retos", que funciona com qualquer *string* (cadeia-de-carateres): +There's an alternative "square bracket notation" that works with any string: ```js run let user = {}; -// cria +// set user["likes birds"] = true; -// lê -alert(user["likes birds"]); // true ('verdadeiro') +// get +alert(user["likes birds"]); // true -// remove +// delete delete user["likes birds"]; ``` -Agora, tudo está bem. Por favor, verifique se a *string* dentro dos parênteses retos está própriamente encerrada entre aspas (qualquer tipo de aspas serve). +Now everything is fine. Please note that the string inside the brackets is properly quoted (any type of quotes will do). -Os parênteses retos, também fornecem uma forma de se obter o nome de uma propriedade como resultado de uma expressão -- em vez de uma *string* literal -- como a partir de uma variável, a exemplo: +Square brackets also provide a way to obtain the property name as the result of any expression -- as opposed to a literal string -- like from a variable as follows: ```js let key = "likes birds"; -// o mesmo que 'user["likes birds"] = true;' +// same as user["likes birds"] = true; user[key] = true; ``` -Aqui, a variável `key` pode ser calculada em tempo de execução (*run-time*) ou depender de uma entrada pelo utilizador (*user input*). E depois a utilizamos para aceder à propriedade. Isso, dá-nos um grande grau de flexibilidade. +Here, the variable `key` may be calculated at run-time or depend on the user input. And then we use it to access the property. That gives us a great deal of flexibility. The dot notation cannot be used in a similar way. -Por exemplo: +For instance: ```js run let user = { @@ -141,13 +140,15 @@ let user = { age: 30 }; -let key = prompt("O que quer saber acerca do utilizador?", "name"); +let key = prompt("What do you want to know about the user?", "name"); -// aceda à variável -alert( user[key] ); // John (se a entrada tiver sido "name") +// access by variable +alert( user[key] ); // John (if enter "name") ``` -A notação por ponto não pode ser usada de forma semelhante: +<<<<<<< HEAD +======= +The dot notation cannot be used in a similar way: ```js run let user = { @@ -158,41 +159,42 @@ let user = { let key = "name"; alert( user.key ) // undefined ``` +>>>>>>> 852ee189170d9022f67ab6d387aeae76810b5923 -### Propriedades computadas +### Computed properties -Podemos utilizar os parênteses retos num object literal. Chamam-se de *propriedades computadas*. +We can use square brackets in an object literal. That's called *computed properties*. -Por exemplo: +For instance: ```js run -let fruit = prompt("Que fruta comprar?", "apple"); +let fruit = prompt("Which fruit to buy?", "apple"); let bag = { *!* - [fruit]: 5, // o nome da propriedade é obtido por meio da variável 'fruit' + [fruit]: 5, // the name of the property is taken from the variable fruit */!* }; alert( bag.apple ); // 5 if fruit="apple" ``` -O significado de uma propriedade computada é simples: `[fruit]` diz que o nome da propriedade é obtido por meio de `fruit`. +The meaning of a computed property is simple: `[fruit]` means that the property name should be taken from `fruit`. -Assim, se um visitante inserir `"apple"`, `bag` se tornará em `{apple: 5}`. +So, if a visitor enters `"apple"`, `bag` will become `{apple: 5}`. -Essencialmente, isso é o mesmo que: +Essentially, that works the same as: ```js run -let fruit = prompt("Que fruta comprar?", "apple"); +let fruit = prompt("Which fruit to buy?", "apple"); let bag = {}; -// obtenha o nome da propriedade por meio da variável fruit +// take property name from the fruit variable bag[fruit] = 5; ``` -...Mas, tem uma melhor apresentação. +...But looks nicer. -Podemos usar expressões mais complexas dentro dos parênteses retos: +We can use more complex expressions inside square brackets: ```js let fruit = 'apple'; @@ -201,14 +203,16 @@ let bag = { }; ``` -Parênteses retos, são mais poderosos que a notação por ponto. Eles permitem quaisquer nomes de propriedades e variáveis. Mas, eles também envolvem mais trabalho para escrever. +Square brackets are much more powerful than the dot notation. They allow any property names and variables. But they are also more cumbersome to write. + +So most of the time, when property names are known and simple, the dot is used. And if we need something more complex, then we switch to square brackets. + -Assim, a maior parte as vezes, quando nomes de propriedades são conhecidos e simples, o ponto é utilizado. E, se precisarmos de algo mais complexo, mudamos para os parênteses retos. ````smart header="Reserved words are allowed as property names" -Uma variável, não pode ter um nome igual a uma das palavras reservadas ('keywords') da linguagem, como "for", "let", "return" etc. +A variable cannot have a name equal to one of language-reserved words like "for", "let", "return" etc. -Mas, para uma propriedade de um objeto, não existe tal restrição. Qualquer nome é aceitável: +But for an object property, there's no such restriction. Any name is fine: ```js run let obj = { @@ -220,27 +224,28 @@ let obj = { alert( obj.for + obj.let + obj.return ); // 6 ``` -Basicamente, qualquer nome é permitido, mas existe um especial: `"__proto__"`, que tem um tratamento particular por razões históricas. Por exemplo, a ele não podemos atribuir um valor não-objeto: +Basically, any name is allowed, but there's a special one: `"__proto__"` that gets special treatment for historical reasons. For instance, we can't set it to a non-object value: ```js run let obj = {}; obj.__proto__ = 5; -alert(obj.__proto__); // [object Object], não resultou como esperado +alert(obj.__proto__); // [object Object], didn't work as intended ``` -Como vemos pelo código, a atribuição do primitivo `5` é ignorada. +As we see from the code, the assignment to a primitive `5` is ignored. -Isso, pode se tornar numa fonte de erros ('bugs') e até de vulnerabilidades, se pretendermos armazenar pares chave-valor arbitrários num objeto, e permitir a um visitante especificar as chaves ('keys'). +That can become a source of bugs and even vulnerabilities if we intend to store arbitrary key-value pairs in an object, and allow a visitor to specify the keys. -Nesse caso, o the visitante pode escolher "__proto__" como chave, e a lógica de atribuição estará arruinada (como se mostra acima). +In that case the visitor may choose "__proto__" as the key, and the assignment logic will be ruined (as shown above). -Existe uma forma de fazer os objetos tratarem `__proto__` como uma propriedade regular, que analisaremos mais adiante, mas primeiro precisamos de saber mais sobre objetos. -Existe também outra estrutura de dados [Map](info:map-set-weakmap-weakset), que aprenderemos no capítulo , que suporta chaves arbitrárias. +There is a way to make objects treat `__proto__` as a regular property, which we'll cover later, but first we need to know more about objects. +There's also another data structure [Map](info:map-set-weakmap-weakset), that we'll learn in the chapter , which supports arbitrary keys. ```` -## Abreviação do valor da propriedade -Em código real, frequentemente empregamos variáveis semelhantes a valores como nomes de propriedades. +## Property value shorthand + +In real code we often use existing variables as values for property names. For instance: @@ -249,7 +254,7 @@ function makeUser(name, age) { return { name: name, age: age - // ...outras propriedades + // ...other properties }; } @@ -257,102 +262,103 @@ let user = makeUser("John", 30); alert(user.name); // John ``` -No exemplo acima, propriedades têm os mesmos nomes que as variáveis. O caso prático (*use-case*) de construir uma propriedade com base numa variável é tão comum, que existe uma especial *abreviação do valor da propriedade* (*property value shorthand*) para a tornar mais curta. +In the example above, properties have the same names as variables. The use-case of making a property from a variable is so common, that there's a special *property value shorthand* to make it shorter. -Em vez de `name:name`, podemos simplesmente escrever `name`, como abaixo: +Instead of `name:name` we can just write `name`, like this: ```js function makeUser(name, age) { *!* return { - name, // o mesmo que name: name - age // o mesmo que age: age + name, // same as name: name + age // same as age: age // ... }; */!* } ``` -Podemos empregar ambas, as propriedades normais e as abreviações (*shorthands*) no mesmo objeto: +We can use both normal properties and shorthands in the same object: ```js let user = { - name, // o mesmo que name:name + name, // same as name:name age: 30 }; ``` -## Verificação de existência +## Existence check -Uma particularidade notável de objetos, é que é possível aceder a qualquer propriedade. Não haverá erro se a propriedade não existir! Aceder a uma propriedade não-existente apenas retorna `undefined`. Ela, fornece uma forma muito comum de testar se a propriedade existe -- aceda, e compare o resultado com *undefined*: +A notable objects feature is that it's possible to access any property. There will be no error if the property doesn't exist! Accessing a non-existing property just returns `undefined`. It provides a very common way to test whether the property exists -- to get it and compare vs undefined: ```js run let user = {}; -alert( user.noSuchProperty === undefined ); // true, significa "propriedade não existente" (no such property) +alert( user.noSuchProperty === undefined ); // true means "no such property" ``` -Também existe um operador especial, `"in"`, para verificar a existência de uma propriedade. - -A sintaxe é: +There also exists a special operator `"in"` to check for the existence of a property. +The syntax is: ```js "key" in object ``` -Por exemplo: +For instance: ```js run let user = { name: "John", age: 30 }; -alert( "age" in user ); // true (verdadeiro), 'user.age' existe -alert( "blabla" in user ); // false (falso), 'user.blabla' não existe +alert( "age" in user ); // true, user.age exists +alert( "blabla" in user ); // false, user.blabla doesn't exist ``` -Por favor, note que no lado esquerdo de `in` deve existir um *nome de propriedade*. Geralmente, é uma *string* entre aspas. +Please note that on the left side of `in` there must be a *property name*. That's usually a quoted string. -Se omitirmos as aspas, isso terá o significado de uma variável contendo o atual nome a ser testado. Por exemplo: +If we omit quotes, that would mean a variable containing the actual name will be tested. For instance: ```js run let user = { age: 30 }; let key = "age"; -alert( *!*key*/!* in user ); // true (verdadeiro), recebe o nome por meio de 'key' e procura por tal propriedade +alert( *!*key*/!* in user ); // true, takes the name from key and checks for such property ``` -````smart header="Using "in" for properties that store "undefined"" -Geralmente, a comparação exata ('strict') para a verificação `"=== undefined"` funciona bem. Mas, existe um caso especial em que falha. Contudo, `"in"` funciona corretamente. +````smart header="Using \"in\" for properties that store `undefined`" +Usually, the strict comparison `"=== undefined"` check works fine. But there's a special case when it fails, but `"in"` works correctly. -É quando uma propriedade de um objeto existe, mas possui `undefined` nela armazenado: +It's when an object property exists, but stores `undefined`: ```js run let obj = { test: undefined }; -alert( obj.test ); // exibe 'undefined', então - tal propriedade não existe? +alert( obj.test ); // it's undefined, so - no such property? -alert( "test" in obj ); // true (verdadeiro), a propriedade na realidade existe! +alert( "test" in obj ); // true, the property does exist! ``` -No código acima, a propriedade `obj.test` tecnicamente existe. Deste modo, o operador `in` funciona corretamente. -Situações como esta muito raramente ocorrem, porque `undefined` não é usualmente atribuido. Em geral, empregamos `null` para valores "desconhecidos" ou "vazios". Deste modo, o operador `in` é um convidado exótico na codificação. +In the code above, the property `obj.test` technically exists. So the `in` operator works right. + +Situations like this happen very rarely, because `undefined` is usually not assigned. We mostly use `null` for "unknown" or "empty" values. So the `in` operator is an exotic guest in the code. ```` -## O laço "for..in" -Para navegar por todas as chaves (*keys*) de um objeto, existe uma forma especial de laço (*loop*): `for..in`. Esta, é uma construção completamente diferente da do `for(;;)`, que estudámos antes. +## The "for..in" loop -A sintaxe: +To walk over all keys of an object, there exists a special form of the loop: `for..in`. This is a completely different thing from the `for(;;)` construct that we studied before. + +The syntax: ```js for (key in object) { - // executa o corpo do laço, por cada chave (key) de entre as propriedades do objeto + // executes the body for each key among object properties } ``` -Por exemplo, vamos imprimir todas propriedades de `user`: +For instance, let's output all properties of `user`: ```js run let user = { @@ -362,32 +368,33 @@ let user = { }; for (let key in user) { - // key (chave) - alert( key ); // 'name', 'age', isAdmin' - // valor por chave (key) + // keys + alert( key ); // name, age, isAdmin + // values for the keys alert( user[key] ); // John, 30, true } ``` -Note, que todas as construções "for" permitem-nos declarar a variável do laço dentro do ciclo (*loop*), como `let key` aqui. +Note that all "for" constructs allow us to declare the looping variable inside the loop, like `let key` here. + +Also, we could use another variable name here instead of `key`. For instance, `"for (let prop in obj)"` is also widely used. -De igual modo, poderíamos usar aqui um nome de variável differente de `key`. Por exemplo, `"for (let prop in obj)"` também é largamente utilizado. -### Ordenado como um objeto +### Ordered like an object -Os objetos são ordenados? Por outras palavras, se percorrermos um objeto com um laço, será que obtemos todas as propriedades pela mesma ordem em que foram adicionadas? Poderemos confiar nisso? +Are objects ordered? In other words, if we loop over an object, do we get all properties in the same order they were added? Can we rely on this? -A curta resposta é: "ordenados de um modo especial" - propriedades inteiras são ordenadas de forma crescente, outras aparecem na ordem em que foram criadas. Detalhes a seguir. +The short answer is: "ordered in a special fashion": integer properties are sorted, others appear in creation order. The details follow. -Como exemplo, considermos um objeto com indicativos telefónicos de países: +As an example, let's consider an object with the phone codes: ```js run let codes = { - "49": "Alemanha", - "41": "Suíça", - "44": "Grã Bretanha", + "49": "Germany", + "41": "Switzerland", + "44": "Great Britain", // .., - "1": "EUA" + "1": "USA" }; *!* @@ -397,59 +404,56 @@ for (let code in codes) { */!* ``` -O objeto, pode ser empregue como sugestão de uma lista de opções para o utilizador. Se, estivermos a construir um *site* maioritariamente para uma audiência Alemã, então provavelmente queremos `49` como o primeiro. +The object may be used to suggest a list of options to the user. If we're making a site mainly for German audience then we probably want `49` to be the first. -Mas, ao correr o código, vemos uma imagem totalmente diferente: +But if we run the code, we see a totally different picture: -- EUA (1) vem em primeiro lugar, -- depois a Suiça (41), e assim por adiante. +- USA (1) goes first +- then Switzerland (41) and so on. -Os indicativos telefónicos, são ordenados por ordem ascendente, porque são inteiros. Por isso, vemos `1, 41, 44, 49`. +The phone codes go in the ascending sorted order, because they are integers. So we see `1, 41, 44, 49`. ````smart header="Integer properties? What's that?" -O termo "propriedade inteira" aqui, significa que uma *string* pode ser convertida para inteiro ('integer') e, de volta reconvertida sem qualquer alteração. +The "integer property" term here means a string that can be converted to-and-from an integer without a change. -Assim, "49" é um nome de propriedade inteiro porque, ao ser transformado num número inteiro e de volta reconvertido, continua o mesmo. Mas, "+49" e "1.2" não são: +So, "49" is an integer property name, because when it's transformed to an integer number and back, it's still the same. But "+49" and "1.2" are not: ```js run -// Math.trunc é uma função incorporada (*built-in function*) que remove a parte decimal - -alert( String(Math.trunc(Number("49"))) ); // "49", inalterado ⇒ propriedade inteira - -alert( String(Math.trunc(Number("+49"))) ); // "49", não o mesmo que "+49" ⇒ não é uma propriedade inteira - -alert( String(Math.trunc(Number("1.2"))) ); // "1", não o mesmo que "1.2" ⇒ não é uma propriedade inteira +// Math.trunc is a built-in function that removes the decimal part +alert( String(Math.trunc(Number("49"))) ); // "49", same, integer property +alert( String(Math.trunc(Number("+49"))) ); // "49", not same "+49" ⇒ not integer property +alert( String(Math.trunc(Number("1.2"))) ); // "1", not same "1.2" ⇒ not integer property ``` ```` -...Por outro lado, se as chaves (*keys*) forem não-inteiras, elas são listadas segundo a ordem em que foram criadas, por exemplo: +...On the other hand, if the keys are non-integer, then they are listed in the creation order, for instance: ```js run let user = { name: "John", surname: "Smith" }; -user.age = 25; // adicione mais uma propriedade +user.age = 25; // add one more *!* -// propriedades não-inteiras são listadas segundo a ordem em que foram criadas +// non-integer properties are listed in the creation order */!* for (let prop in user) { - alert( prop ); // 'name', 'surname', 'age' + alert( prop ); // name, surname, age } ``` -Portanto, para corrigir o problema dos indicativos telefónicos, podemos "aldrabar" tornando-os não-inteiros. Adicionar um sinal de mais `"+"`, antes de cada código é o suficiente. +So, to fix the issue with the phone codes, we can "cheat" by making the codes non-integer. Adding a plus `"+"` sign before each code is enough. -Desta forma: +Like this: ```js run let codes = { - "+49": "Alemanha", - "+41": "Suiça", - "+44": "Grã Bretanha", + "+49": "Germany", + "+41": "Switzerland", + "+44": "Great Britain", // .., - "+1": "EUA" + "+1": "USA" }; for (let code in codes) { @@ -457,30 +461,30 @@ for (let code in codes) { } ``` -Agora, funciona como pretendido. +Now it works as intended. -## Cópia por referência +## Copying by reference -Uma das principais diferenças entre objetos vs primitivos, está em que os primeiros são armazenados e copiados "por referência" (*by reference*). +One of the fundamental differences of objects vs primitives is that they are stored and copied "by reference". -Valores primitivos: *strings*, números, booleanos -- são atribuidos/copiados como "o próprio valor". +Primitive values: strings, numbers, booleans -- are assigned/copied "as a whole value". -Por exemplo: +For instance: ```js let message = "Hello!"; let phrase = message; ``` -Como resultado, temos duas variáveis independentes, mas cada uma armazenando a *string* (cadeia-de-carateres) `"Hello!"`. +As a result we have two independent variables, each one is storing the string `"Hello!"`. ![](variable-copy-value.svg) -Objetos não são assim. +Objects are not like that. -**Uma variável não armazena o próprio objeto, mas o seu "endereço em memória" (*address in memory*), por outras palavras "uma referência" (*reference*) a ele.** +**A variable stores not the object itself, but its "address in memory", in other words "a reference" to it.** -Aqui, está a imagem para o objeto: +Here's the picture for the object: ```js let user = { @@ -490,25 +494,25 @@ let user = { ![](variable-contains-reference.svg) -Aqui, o objeto é armazenado algures na memória. E a variável `user` contém uma "referência" para ele. +Here, the object is stored somewhere in memory. And the variable `user` has a "reference" to it. -**Quando uma variável com um objeto é copiada -- é a referência copiada, o objeto não é duplicado.** +**When an object variable is copied -- the reference is copied, the object is not duplicated.** -Se imaginarmos um objeto como um fichário, então uma variável será uma chave (*a key*) para ele. Copiando uma variável duplica a chave (*the key*), não o próprio fichário. +If we imagine an object as a cabinet, then a variable is a key to it. Copying a variable duplicates the key, but not the cabinet itself. -Por exemplo: +For instance: ```js no-beautify let user = { name: "John" }; -let admin = user; // copia a referência +let admin = user; // copy the reference ``` -Agora, temos duas variáveis, e cada uma com a referência para o mesmo objeto: +Now we have two variables, each one with the reference to the same object: ![](variable-copy-reference.svg) -Podemos utilizar qualquer das variáveis, para aceder ao fichário e alterar o seu conteúdo: +We can use any variable to access the cabinet and modify its contents: ```js run let user = { name: 'John' }; @@ -516,46 +520,46 @@ let user = { name: 'John' }; let admin = user; *!* -admin.name = 'Pete'; // alterado através da referência em "admin" +admin.name = 'Pete'; // changed by the "admin" reference */!* -alert(*!*user.name*/!*); // 'Pete', as alterações também são visíveis por meio da referência em "user" +alert(*!*user.name*/!*); // 'Pete', changes are seen from the "user" reference ``` -O exemplo acima, demonstra que apenas existe um objecto. Como se tivéssemos um fichário com duas chaves, e usássemos uma delas (`admin`) para o aceder. E depois, se mais tarde usássemos a outra chave (`user`) poderíamos ver as alterações. +The example above demonstrates that there is only one object. As if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use the other key (`user`) we would see changes. -### Comparação por referência +### Comparison by reference -Os operadores de igualdade `==` e de igualdade exata (*strict*) `===` para objetos funcionam exatamente da mesma forma. +The equality `==` and strict equality `===` operators for objects work exactly the same. -**Dois objetos apenas são iguais se eles forem o mesmo objeto.** +**Two objects are equal only if they are the same object.** -Por exemplo, duas variáveis referenciam o mesmo objeto, elas são iguais: +For instance, two variables reference the same object, they are equal: ```js run let a = {}; -let b = a; // cópia por referência +let b = a; // copy the reference -alert( a == b ); // true (verdadeiro), ambas as variáveis referenciam o mesmo objeto -alert( a === b ); // true (verdadeiro) +alert( a == b ); // true, both variables reference the same object +alert( a === b ); // true ``` -E aqui, dois objetos independentes não são iguais, muito embora ambos sejam vazios: +And here two independent objects are not equal, even though both are empty: ```js run let a = {}; -let b = {}; // dois objetos independentes +let b = {}; // two independent objects -alert( a == b ); // false (falso) +alert( a == b ); // false ``` -Para comparações como `obj1 > obj2` ou para uma comparação com um primitivo `obj == 5`, objetos são convertidos para primitivos. Estudaremos como funciona a conversão de objetos muito em breve, mas para dizer a verdade, tais comparações são muito raramente necessárias e são geralmente o resultado de um erro de código. +For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj == 5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons are necessary very rarely and usually are a result of a coding mistake. -### Objeto constante +### Const object -Um objeto declarado com `const` *pode* ser alterado. +An object declared as `const` *can* be changed. -Por exemplo: +For instance: ```js run const user = { @@ -569,9 +573,9 @@ user.age = 25; // (*) alert(user.age); // 25 ``` -Parece que a linha `(*)` irá causar um erro, mas não, não há totalmente qualquer problema. Isso, porque `const` apenas fixa o valor de `user`. Então, aqui `user` armazena uma referência para um mesmo objeto pelo tempo todo. A linha `(*)` vai para *dentro* do objeto, não faz uma re-atribuição a `user`. +It might seem that the line `(*)` would cause an error, but no, there's totally no problem. That's because `const` fixes the value of `user` itself. And here `user` stores the reference to the same object all the time. The line `(*)` goes *inside* the object, it doesn't reassign `user`. -A `const` produzirá um erro se tentarmos colocar em `user` qualquer outra coisa, por exemplo: +The `const` would give an error if we try to set `user` to something else, for instance: ```js run const user = { @@ -579,26 +583,26 @@ const user = { }; *!* -// Erro (não é possível reatribuir a 'user') +// Error (can't reassign user) */!* user = { name: "Pete" }; ``` -...Mas, se quisermos tornar as propriedades do objeto constantes? Então, aí `user.age = 25` produzirá um erro. Isso, também é possível. Iremos cobrir isto no capítulo . +...But what if we want to make constant object properties? So that `user.age = 25` would give an error. That's possible too. We'll cover it in the chapter . -## Clonar e fundir, Object.assign +## Cloning and merging, Object.assign -Portanto, a cópia de uma variável de objeto cria mais uma referência para o mesmo objeto. +So, copying an object variable creates one more reference to the same object. -Mas, se quisermos duplicar um objecto? Criar uma cópia independente, um *clone*? +But what if we need to duplicate an object? Create an independent copy, a clone? -Também se pode fazer, mas é um pouco mais difícil, porque não existe método incorporado (*built-in*) ao JavaScript para isso. Na verdade, isso raramente é necessário. A cópia por referência é a maior parte das vezes boa. +That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. Actually, that's rarely needed. Copying by reference is good most of the time. -Mas, se realmente quisermos isto, aí precisaremos de criar um novo objeto e replicar a estrutura do existente iterando pelas suas propriedades e copiando-as, digamos num nível primitivo. +But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level. -Desta forma: +Like this: ```js run let user = { @@ -607,32 +611,32 @@ let user = { }; *!* -let clone = {}; // o novo objeto vazio +let clone = {}; // the new empty object -// copiemos todas as propriedades de 'user' para aquele +// let's copy all user properties into it for (let key in user) { clone[key] = user[key]; } */!* -// agora,'clone' é um clone completamente independente -clone.name = "Pete"; // altere dados nele +// now clone is a fully independent clone +clone.name = "Pete"; // changed the data in it -alert( user.name ); // contudo, ainda está 'John' no objeto original +alert( user.name ); // still John in the original object ``` -Podemos também empregar o método [Object.assign](mdn:js/Object/assign) para isso. +Also we can use the method [Object.assign](mdn:js/Object/assign) for that. -A sintaxe é: +The syntax is: ```js Object.assign(dest, [src1, src2, src3...]) ``` -- Os argumentos `dest`, e `src1, ..., srcN` (que podem ser tantos quantos necessários) são objetos. -- Ele copia as propriedades de todos os objects `src1, ..., srcN` para `dest`. Por outras palavras, propriedades de todos os objetos, a começar pelo segundo, são copiadas para o primeiro. Depois, ele retorna `dest`. +- Arguments `dest`, and `src1, ..., srcN` (can be as many as needed) are objects. +- It copies the properties of all objects `src1, ..., srcN` into `dest`. In other words, properties of all arguments starting from the 2nd are copied into the 1st. Then it returns `dest`. -Por exemplo, podemos utilizá-lo para fundir vários objetos num só: +For instance, we can use it to merge several objects into one: ```js let user = { name: "John" }; @@ -640,25 +644,25 @@ let permissions1 = { canView: true }; let permissions2 = { canEdit: true }; *!* -// copia todas propriedades de 'permissions1' e 'permissions2' para 'user' +// copies all properties from permissions1 and permissions2 into user Object.assign(user, permissions1, permissions2); */!* -// agora, user = { name: "John", canView: true, canEdit: true } +// now user = { name: "John", canView: true, canEdit: true } ``` -Se, o objeto recetor (`user`) já tiver alguma propriedade com o mesmo nome, ela será substituída (*overwritten*): +If the receiving object (`user`) already has the same named property, it will be overwritten: ```js let user = { name: "John" }; -// substitua ('overwrite') 'nome', e adicione 'isAdmin' +// overwrite name, add isAdmin Object.assign(user, { name: "Pete", isAdmin: true }); -// agora, user = { name: "Pete", isAdmin: true } +// now user = { name: "Pete", isAdmin: true } ``` -Podemos também utilizar `Object.assign` para substituir o ciclo (*loop*) acima para uma clonagem simples: +We also can use `Object.assign` to replace the loop for simple cloning: ```js let user = { @@ -671,12 +675,11 @@ let clone = Object.assign({}, user); */!* ``` -Ele copia todas as propriedades de `user` para o objecto vazio e retorna este. Na verdade, é o mesmo laço (*loop*), mas mais curto. - -Até agora, assumimos que todas as propriedades de `user` são primitivas. Mas, propriedades podem ser referências para outros objetos. O que fazer nesse caso? +It copies all properties of `user` into the empty object and returns it. Actually, the same as the loop, but shorter. -Como aqui: +Until now we assumed that all properties of `user` are primitive. But properties can be references to other objects. What to do with them? +Like this: ```js run let user = { name: "John", @@ -689,10 +692,9 @@ let user = { alert( user.sizes.height ); // 182 ``` -Agora, não é suficiente efetuar a cópia `clone.sizes = user.sizes`, porque `user.sizes` é um objeto, e aí seria copiado por referência. Então, `clone` e `user` iriam partilhar a mesma propriedade "*sizes*": - -Deste modo: +Now it's not enough to copy `clone.sizes = user.sizes`, because the `user.sizes` is an object, it will be copied by reference. So `clone` and `user` will share the same sizes: +Like this: ```js run let user = { name: "John", @@ -704,48 +706,49 @@ let user = { let clone = Object.assign({}, user); -alert( user.sizes === clone.sizes ); // true (verdadeiro), é o mesmo objeto +alert( user.sizes === clone.sizes ); // true, same object -// 'user' e 'clone' partilham 'sizes' -user.sizes.width++; // altere uma propriedade num lugar -alert(clone.sizes.width); // 51, e verá o resultado a partir do outro +// user and clone share sizes +user.sizes.width++; // change a property from one place +alert(clone.sizes.width); // 51, see the result from the other one ``` -Para corrigir isso, deveriamos empregar o laço (*loop*) para clonagem, que examina cada valor de `user[key]` e, se for um objeto, então também replica essa estrutura. Essa, é chamada de uma "clonagem profunda" ("*deep cloning*"). +To fix that, we should use the cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning". + +There's a standard algorithm for deep cloning that handles the case above and more complex cases, called the [Structured cloning algorithm](http://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data). In order not to reinvent the wheel, we can use a working implementation of it from the JavaScript library [lodash](https://lodash.com), the method is called [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). + -Existe um algoritmo padrão (*standard*) para clonagem profunda (deep cloning), que trata tanto do caso acima como de mais complexos, chamado de [Structured cloning algorithm](http://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data) (algoritmo de clonagem de estruturas). Para não se reinventar a roda, poderemos utilizar uma implementação operacional do mesmo disponível na biblioteca (*library*) de JavaScript [lodash](https://lodash.com), o método é chamado [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). -## Sumário +## Summary -Objetos são *arrays* associativos (*associative arrays*), com várias funcionalidades especiais. +Objects are associative arrays with several special features. -Eles armazenam propriedades em pares chave-valor, onde: -- As chaves das propriedades devem ser *strings* ou símbolos (geralmente *strings*). -- Valores podem ser de qualquer tipo. +They store properties (key-value pairs), where: +- Property keys must be strings or symbols (usually strings). +- Values can be of any type. -Para aceder a uma propriedade, podemos utilizar: -- A notação por ponto: `obj.property`. -- A notação por parênteses retos `obj["property"]`. Os parênteses retos permitem receber a chave de uma variável, como por exemplo `obj[varWithKey]`. +To access a property, we can use: +- The dot notation: `obj.property`. +- Square brackets notation `obj["property"]`. Square brackets allow to take the key from a variable, like `obj[varWithKey]`. -Operadores adicionais: -- Para remover uma propriedade: `delete obj.prop`. -- Para verificar se uma propriedade com uma dada chave existe: `"key" in obj`. -- Para iterar sobre um objeto: o ciclo `for (let key in obj)`. +Additional operators: +- To delete a property: `delete obj.prop`. +- To check if a property with the given key exists: `"key" in obj`. +- To iterate over an object: `for (let key in obj)` loop. -Objetos são atribuidos e copiados por referência. Por outras palavras, uma variável não armazena o "valor do objeto", mas uma "referência" (endereço em memória) do valor. Assim, copiar tal variável ou passá-la como argumento de uma função copia tal referência, não o objeto. Todas as operações sobre cópias de referências (como adicionar/remover propriedades) são executadas sobre um mesmo único objeto. +Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object. All operations via copied references (like adding/removing properties) are performed on the same single object. - Para efetuar uma "verdadeira cópia" (um clone), podemos utilizar `Object.assign` ou [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). +To make a "real copy" (a clone) we can use `Object.assign` or [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep). -O que estudámos neste capítulo é o chamado "objeto simples" ("*plain object*"), ou simplesmente `Objeto`. +What we've studied in this chapter is called a "plain object", or just `Object`. -Existem muitos outros tipos de objetos em JavaScript: +There are many other kinds of objects in JavaScript: -- `Array` para armazenar coleções de dados ordenadas, -- `Date` para armazenar informação sobre data e tempo, -- `Error` para armazenar informação sobre um erro. -- ...E outros mais. +- `Array` to store ordered data collections, +- `Date` to store the information about the date and time, +- `Error` to store the information about an error. +- ...And so on. -Eles têm as suas funcionalidades especiais, que estudaremos mais adiante. Por vezes, pessoas dizem algo como "o tipo -Array" ou "o tipo Data" (*Date*), mas formalmente eles não são própriamente tipos, mas pertencem a um único tipo de dados "objeto". E o extendem de várias formas. +They have their special features that we'll study later. Sometimes people say something like "Array type" or "Date type", but formally they are not types of their own, but belong to a single "object" data type. And they extend it in various ways. -Objetos em JavaScript são muito poderosos. Aqui, apenas tocámos na superfície de um realmente amplo tópico. Iremos, mais especificamente, trabalhar e aprender sobre objetos em futuras partes do tutorial. +Objects in JavaScript are very powerful. Here we've just scratched the surface of a topic that is really huge. We'll be closely working with objects and learning more about them in further parts of the tutorial. diff --git a/1-js/04-object-basics/index.md b/1-js/04-object-basics/index.md index 991117d25..d2387aafa 100644 --- a/1-js/04-object-basics/index.md +++ b/1-js/04-object-basics/index.md @@ -1 +1 @@ -# Objetos: o básico +# Objects: the basics From 17661423402b6bc219d6c0d607fe17a5462c7c53 Mon Sep 17 00:00:00 2001 From: odsantos Date: Thu, 12 Dec 2019 21:12:43 +0100 Subject: [PATCH 3/3] add translation to string directory files --- .../03-string/1-ucfirst/_js.view/test.js | 4 +- .../03-string/1-ucfirst/solution.md | 15 +- .../05-data-types/03-string/1-ucfirst/task.md | 7 +- .../03-string/2-check-spam/_js.view/test.js | 12 +- .../03-string/2-check-spam/solution.md | 9 +- .../03-string/2-check-spam/task.md | 15 +- .../03-string/3-truncate/_js.view/test.js | 12 +- .../03-string/3-truncate/solution.md | 6 +- .../03-string/3-truncate/task.md | 14 +- .../4-extract-currency/_js.view/test.js | 2 +- .../03-string/4-extract-currency/task.md | 10 +- 1-js/05-data-types/03-string/article.md | 520 +++++++++--------- 12 files changed, 307 insertions(+), 319 deletions(-) diff --git a/1-js/05-data-types/03-string/1-ucfirst/_js.view/test.js b/1-js/05-data-types/03-string/1-ucfirst/_js.view/test.js index d5c50ff57..c0d691dc1 100644 --- a/1-js/05-data-types/03-string/1-ucfirst/_js.view/test.js +++ b/1-js/05-data-types/03-string/1-ucfirst/_js.view/test.js @@ -1,9 +1,9 @@ describe("ucFirst", function() { - it('Uppercases the first symbol', function() { + it('Primeiro símbolo em maiúsculas', function() { assert.strictEqual(ucFirst("john"), "John"); }); - it("Doesn't die on an empty string", function() { + it("Não aborta numa string vazia", function() { assert.strictEqual(ucFirst(""), ""); }); }); \ No newline at end of file diff --git a/1-js/05-data-types/03-string/1-ucfirst/solution.md b/1-js/05-data-types/03-string/1-ucfirst/solution.md index 4809cf123..c9e1e3925 100644 --- a/1-js/05-data-types/03-string/1-ucfirst/solution.md +++ b/1-js/05-data-types/03-string/1-ucfirst/solution.md @@ -1,19 +1,19 @@ -We can't "replace" the first character, because strings in JavaScript are immutable. +Não podemos "substituir" o primeiro carátere, porque *strings* em JavaScript são imutáveis. -But we can make a new string based on the existing one, with the uppercased first character: +Mas podemos criar uma nova *string* com base na existente, com o primeiro carátere em maiúsculas: ```js let newStr = str[0].toUpperCase() + str.slice(1); ``` -There's a small problem though. If `str` is empty, then `str[0]` is undefined, so we'll get an error. +Contudo, há um pequeno problema. Se `str` estiver vazia, então `str[0]` é *undefined*, e assim obtemos um erro. -There are two variants here: +Existem duas variantes aqui: -1. Use `str.charAt(0)`, as it always returns a string (maybe empty). -2. Add a test for an empty string. +1. Use `str.charAt(0)`, porque sempre retorna uma *string* (por vezes vazia). +2. Adicione um teste por uma *string* vazia. -Here's the 2nd variant: +Aqui está a segunda variante: ```js run function ucFirst(str) { @@ -24,4 +24,3 @@ function ucFirst(str) { alert( ucFirst("john") ); // John ``` - diff --git a/1-js/05-data-types/03-string/1-ucfirst/task.md b/1-js/05-data-types/03-string/1-ucfirst/task.md index c0e6ecac4..413df6714 100644 --- a/1-js/05-data-types/03-string/1-ucfirst/task.md +++ b/1-js/05-data-types/03-string/1-ucfirst/task.md @@ -1,12 +1,11 @@ -importance: 5 +importância: 5 --- -# Uppercast the first character +# Primeiro carátere em maiúsculas -Write a function `ucFirst(str)` that returns the string `str` with the uppercased first character, for instance: +Escreva uma função `ucFirst(str)` que retorne a *string* `str` com o primeiro carátere em maiúsculas, por exemplo: ```js ucFirst("john") == "John"; ``` - diff --git a/1-js/05-data-types/03-string/2-check-spam/_js.view/test.js b/1-js/05-data-types/03-string/2-check-spam/_js.view/test.js index 85eb24fcb..c8e94cd72 100644 --- a/1-js/05-data-types/03-string/2-check-spam/_js.view/test.js +++ b/1-js/05-data-types/03-string/2-check-spam/_js.view/test.js @@ -1,13 +1,13 @@ describe("checkSpam", function() { - it('finds spam in "buy ViAgRA now"', function() { - assert.isTrue(checkSpam('buy ViAgRA now')); + it('encontra spam em "compre ViAgRA agora"', function() { + assert.isTrue(checkSpam('compre ViAgRA agora')); }); - it('finds spam in "free xxxxx"', function() { - assert.isTrue(checkSpam('free xxxxx')); + it('encontra spam em "xxxxx grátis"', function() { + assert.isTrue(checkSpam('xxxxx grátis')); }); - it('no spam in "innocent rabbit"', function() { - assert.isFalse(checkSpam('innocent rabbit')); + it('não encontra spam em "coelha inocente"', function() { + assert.isFalse(checkSpam('coelha inocente')); }); }); \ No newline at end of file diff --git a/1-js/05-data-types/03-string/2-check-spam/solution.md b/1-js/05-data-types/03-string/2-check-spam/solution.md index 893c26497..f3d60e266 100644 --- a/1-js/05-data-types/03-string/2-check-spam/solution.md +++ b/1-js/05-data-types/03-string/2-check-spam/solution.md @@ -1,4 +1,4 @@ -To make the search case-insensitive, let's bring the string to lower case and then search: +Para tornar a pesquisa não sensível a maiúsculas/minúsculas (*case-insensitive*), vamos transformar a *string* em minúsculas e depois efetuar a pesquisa: ```js run function checkSpam(str) { @@ -7,8 +7,7 @@ function checkSpam(str) { return lowerStr.includes('viagra') || lowerStr.includes('xxx'); } -alert( checkSpam('buy ViAgRA now') ); -alert( checkSpam('free xxxxx') ); -alert( checkSpam("innocent rabbit") ); +alert( checkSpam('compre ViAgRA agora') ); +alert( checkSpam('xxxxx grátis') ); +alert( checkSpam("coelha inocente") ); ``` - diff --git a/1-js/05-data-types/03-string/2-check-spam/task.md b/1-js/05-data-types/03-string/2-check-spam/task.md index d073adc05..34daf3a79 100644 --- a/1-js/05-data-types/03-string/2-check-spam/task.md +++ b/1-js/05-data-types/03-string/2-check-spam/task.md @@ -1,16 +1,15 @@ -importance: 5 +importância: 5 --- -# Check for spam +# Verifica por spam -Write a function `checkSpam(str)` that returns `true` if `str` contains 'viagra' or 'XXX', otherwise `false. +Escreva uma função `checkSpam(str)` que retorne `true` se `str` contiver 'viagra' ou 'XXX', e caso contrário retorne `false`. -The function must be case-insensitive: +A função não deve ser sensível a maiúsculas/minúsculas (*case-insensitive*): ```js -checkSpam('buy ViAgRA now') == true -checkSpam('free xxxxx') == true -checkSpam("innocent rabbit") == false +checkSpam('compre ViAgRA agora') == true +checkSpam('xxxxx grátis') == true +checkSpam("coelha inocente") == false ``` - diff --git a/1-js/05-data-types/03-string/3-truncate/_js.view/test.js b/1-js/05-data-types/03-string/3-truncate/_js.view/test.js index 991492331..3557f2f12 100644 --- a/1-js/05-data-types/03-string/3-truncate/_js.view/test.js +++ b/1-js/05-data-types/03-string/3-truncate/_js.view/test.js @@ -1,15 +1,15 @@ describe("truncate", function() { - it("truncate the long string to the given length (including the ellipsis)", function() { + it("trunque a string comprida para o comprimento pretendido (incluindo as reticências)", function() { assert.equal( - truncate("What I'd like to tell on this topic is:", 20), - "What I'd like to te…" + truncate("O que eu gostaria de dizer neste tópico é:", 20), + "O que eu gostaria d…" ); }); - it("doesn't change short strings", function() { + it("não altera strings curtas", function() { assert.equal( - truncate("Hi everyone!", 20), - "Hi everyone!" + truncate("Olá a todos!", 20), + "Olá a todos!" ); }); diff --git a/1-js/05-data-types/03-string/3-truncate/solution.md b/1-js/05-data-types/03-string/3-truncate/solution.md index 5546c47ee..01cde0181 100644 --- a/1-js/05-data-types/03-string/3-truncate/solution.md +++ b/1-js/05-data-types/03-string/3-truncate/solution.md @@ -1,8 +1,8 @@ -The maximal length must be `maxlength`, so we need to cut it a little shorter, to give space for the ellipsis. +O comprimento máximo deve ser `maxlength`, assim precisamos de a cortar um pouco antes, para dar espaço às reticências (*ellipsis*). -Note that there is actually a single unicode character for an ellipsis. That's not three dots. +Note que na verdade existe apenas um único carátere *unicode* para as reticências. Não são três pontos. -```js run demo +```js execute demo function truncate(str, maxlength) { return (str.length > maxlength) ? str.slice(0, maxlength - 1) + '…' : str; diff --git a/1-js/05-data-types/03-string/3-truncate/task.md b/1-js/05-data-types/03-string/3-truncate/task.md index 6382029f4..b5e8b7d29 100644 --- a/1-js/05-data-types/03-string/3-truncate/task.md +++ b/1-js/05-data-types/03-string/3-truncate/task.md @@ -1,17 +1,17 @@ -importance: 5 +importância: 5 --- -# Truncate the text +# Trunque o texto -Create a function `truncate(str, maxlength)` that checks the length of the `str` and, if it exceeds `maxlength` -- replaces the end of `str` with the ellipsis character `"…"`, to make its length equal to `maxlength`. +Crie uma função `truncate(str, maxlength)` que verifique o comprimento de `str` e, se exceder a `maxlength` -- substitua o final de `str` pelo carátere reticências `"…"`, afim de tornar o seu comprimento igual a `maxlength`. -The result of the function should be the truncated (if needed) string. +O resultado da função deverá ser a *string* truncada (se necessário). -For instance: +Por exemplo: ```js -truncate("What I'd like to tell on this topic is:", 20) = "What I'd like to te…" +truncate("O que eu gostaria de dizer neste tópico é:", 20) = "O que eu gostaria d…" -truncate("Hi everyone!", 20) = "Hi everyone!" +truncate("Olá a todos!", 20) = "Olá a todos!" ``` diff --git a/1-js/05-data-types/03-string/4-extract-currency/_js.view/test.js b/1-js/05-data-types/03-string/4-extract-currency/_js.view/test.js index 1c3f0bbc1..20c44f9e3 100644 --- a/1-js/05-data-types/03-string/4-extract-currency/_js.view/test.js +++ b/1-js/05-data-types/03-string/4-extract-currency/_js.view/test.js @@ -1,6 +1,6 @@ describe("extractCurrencyValue", function() { - it("for the string $120 returns the number 120", function() { + it("para a string $120 retorne o número 120", function() { assert.strictEqual(extractCurrencyValue('$120'), 120); }); diff --git a/1-js/05-data-types/03-string/4-extract-currency/task.md b/1-js/05-data-types/03-string/4-extract-currency/task.md index feb16e642..fd321bd70 100644 --- a/1-js/05-data-types/03-string/4-extract-currency/task.md +++ b/1-js/05-data-types/03-string/4-extract-currency/task.md @@ -1,16 +1,16 @@ -importance: 4 +importância: 4 --- -# Extract the money +# Extraia o dinheiro -We have a cost in the form `"$120"`. That is: the dollar sign goes first, and then the number. +Temos um custo na forma `"$120"`. Isto é: o sinal de dólar vem primeiro, e depois o número. -Create a function `extractCurrencyValue(str)` that would extract the numeric value from such string and return it. +Crie uma função `extractCurrencyValue(str)`, que irá extrair o valor numérico dessa *string* e o retornar. The example: ```js -alert( extractCurrencyValue('$120') === 120 ); // true +alert( extractCurrencyValue('$120') === 120 ); // true (verdadeiro) ``` diff --git a/1-js/05-data-types/03-string/article.md b/1-js/05-data-types/03-string/article.md index b7e619188..7235c603e 100644 --- a/1-js/05-data-types/03-string/article.md +++ b/1-js/05-data-types/03-string/article.md @@ -1,23 +1,23 @@ -# Strings +# *Strings* -In JavaScript, the textual data is stored as strings. There is no separate type for a single character. +Em JavaScript, os dados de texto são armazenados como *strings* (cadeias-de-carateres). Não existe um tipo separado para um único carátere. -The internal format for strings is always [UTF-16](https://en.wikipedia.org/wiki/UTF-16), it is not tied to the page encoding. +O formato interno das *strings* é sempre em [UTF-16](https://en.wikipedia.org/wiki/UTF-16), por isso não está relacionado à codificação da página (*page encoding*). -## Quotes +## Aspas -Let's recall the kinds of quotes. +Vamos relembrar os tipos de aspas. -Strings can be enclosed within either single quotes, double quotes or backticks: +*Strings* podem estar dentro de aspas simples, aspas duplas ou acentos graves (*backticks*): ```js -let single = 'single-quoted'; -let double = "double-quoted"; +let single = 'entre aspas simples'; +let double = "entre aspas duplas"; -let backticks = `backticks`; +let backticks = `entre acentos graves`; ``` -Single and double quotes are essentially the same. Backticks, however, allow us to embed any expression into the string, including function calls: +Aspas simples e duplas são essencialmente o mesmo. *Backticks*, contudo, permitem-nos incorporar qualquer expressão numa *string*, incluindo chamadas de funções: ```js run function sum(a, b) { @@ -27,245 +27,241 @@ function sum(a, b) { alert(`1 + 2 = ${sum(1, 2)}.`); // 1 + 2 = 3. ``` -Another advantage of using backticks is that they allow a string to span multiple lines: +Uma outra vantagem em usar *backticks*, está em que eles permitem a uma *string* estender-se por múltiplas linhas: ```js run -let guestList = `Guests: +let guestList = `Convidados: * John * Pete * Mary `; -alert(guestList); // a list of guests, multiple lines +alert(guestList); // uma lista de convidados, múltiplas linhas ``` -If we try to use single or double quotes in the same way, there will be an error: +Se tentarmos utilizar aspas simples ou duplas, da mesma forma, haverá um erro: ```js run -let guestList = "Guests: // Error: Unexpected token ILLEGAL +let guestList = "Convidados: // Error: Unexpected token ILLEGAL * John"; + // (Erro símbolo-sintático [token] inesperado ILEGAL * John) ``` -Single and double quotes come from ancient times of language creation when the need for multiline strings was not taken into account. Backticks appeared much later and thus are more versatile. +Aspas simples ou duplas vêm de tempos antigos da criação da linguagem, quando a necessidade de *strings* multi-linha não era considerada. Os *backticks* apareceram muito mais tarde e portanto são mais versáteis. -Backticks also allow us to specify a "template function" before the first backtick. The syntax is: func`string`. The function `func` is called automatically, receives the string and embedded expressions and can process them. You can read more about it in the [docs](mdn:/JavaScript/Reference/Template_literals#Tagged_template_literals). This is called "tagged templates". This feature makes it easier to wrap strings into custom templating or other functionality, but it is rarely used. +Os *backticks* também nos permitem especifcar uma "função modelo" (*template function*) antes do primeiro *backtick*. A sintaxe é: func`string`. A função `func` é chamada automaticamente, recebe a *string* e expressões nesta incorporadas, e depois pode prosseguir. Você poderá ler mais sobre isso nos [docs](mdn:/JavaScript/Reference/Template_literals#Tagged_template_literals). Isto é chamado de "modelos etiquetados" (*tagged templates*). Esta funcionalidade torna mais fácil embeber *strings* em modelos personalizados ou noutras funcionalidades, mas raramente é utilizada. +## Carateres especiais -## Special characters - -It is still possible to create multiline strings with single quotes by using a so-called "newline character", written as `\n`, which denotes a line break: +Ainda é possível criar *strings* multi-linha com aspas simples utilizando o chamado "carátere de nova-linha", escrito como `\n`, que denota uma quebra de linha: ```js run -let guestList = "Guests:\n * John\n * Pete\n * Mary"; +let guestList = "Convidados\n * John\n * Pete\n * Mary"; -alert(guestList); // a multiline list of guests +alert(guestList); // uma lista de convidados em múltiplas linhas ``` -For example, these two lines describe the same: +Por exemplo, estas duas linhas descrevem o mesmo: ```js run -alert( "Hello\nWorld" ); // two lines using a "newline symbol" +alert( "Hello\nWorld" ); // duas linhas utilizando o "símbolo de nova-linha" -// two lines using a normal newline and backticks +// duas linhas utilizando uma quebra de linha normal e backticks alert( `Hello World` ); ``` -There are other, less common "special" characters as well. Here's the list: +Existem outros, mas menos comuns carateres "especiais". Aqui está a lista: -| Character | Description | +| Carátere | Descrição | |-----------|-------------| |`\b`|Backspace| |`\f`|Form feed| |`\n`|New line| |`\r`|Carriage return| |`\t`|Tab| -|`\uNNNN`|A unicode symbol with the hex code `NNNN`, for instance `\u00A9` -- is a unicode for the copyright symbol `©`. It must be exactly 4 hex digits. | -|`\u{NNNNNNNN}`|Some rare characters are encoded with two unicode symbols, taking up to 4 bytes. This long unicode requires braces around it.| +|`\uNNNN`|Um símbolo *unicode* com código hexadecimal `NNNN`; por exemplo `\u00A9` -- é um *unicode* para o símbolo direitos-do-autor (*copyright*) `©`. Devem ser exatamente 4 dígitos hexadecimais. | +|`\u{NNNNNNNN}`|Alguns carateres raros são codificados com dois símbolos *unicode*, tomando até 4 *bytes*. Este longo *unicode* requere chavetas à sua volta.| -Examples with unicode: +Exemplos com *unicode*: ```js run alert( "\u00A9" ); // © -alert( "\u{20331}" ); // 佫, a rare chinese hieroglyph (long unicode) -alert( "\u{1F60D}" ); // 😍, a smiling face symbol (another long unicode) +alert( "\u{20331}" ); // 佫, um hieróglifo chinês raro (longo unicode) +alert( "\u{1F60D}" ); // 😍, um símbolo de face sorridente (outro longo unicode) ``` -All special characters start with a backslash character `\`. It is also called an "escape character". +Todos os carateres especiais começam por um carátere de barra-invertida (*backslash*) `\`. Também é chamado de "*escape character*" (carátere de escape). -We would also use it if we want to insert a quote into the string. +Também o utilizamos quando queremos inserir uma das aspas dentro de uma *string*. -For instance: +Por exemplo: ```js run alert( 'I*!*\'*/!*m the Walrus!' ); // *!*I'm*/!* the Walrus! ``` -As you can see, we have to prepend the inner quote by the backslash `\'`, because otherwise it would indicate the string end. +Como podemos ver, precedemos a aspas interior por backslash `\'`, porque de outra forma ela indicaria o final da *string*. -Of course, that refers only to the quotes that are same as the enclosing ones. So, as a more elegant solution, we could switch to double quotes or backticks instead: +Evidentemente, isto apenas se refere às aspas iguais às de abertura e fecho. Deste modo, como uma solução mais elegante, poderíamos substitui-las por aspas duplas ou backticks: ```js run alert( `I'm the Walrus!` ); // I'm the Walrus! ``` -Note that the backslash `\` serves for the correct reading of the string by JavaScript, then disappears. The in-memory string has no `\`. You can clearly see that in `alert` from the examples above. +Note que a *backslash* `\` serve para a correta leitura da *string* por JavaScript, e depois ela desaparece. A *string* em memória não possui nenhuma `\`. Pode claramente ver nos `alert` dos exemplos anteriores. -But what if we need to show an actual backslash `\` within the string? +Mas, se precisarmos de realmente mostrar uma *backslash* `\` dentro de uma *string*? -That's possible, but we need to double it like `\\`: +Isto é possível, mas precisamos de a duplicar, como `\\`: ```js run -alert( `The backslash: \\` ); // The backslash: \ +alert( `A backslash: \\` ); // A backslash: \ ``` -## String length - +## Comprimento da *string* -The `length` property has the string length: +A propriedade `length` possui o comprimento da *string*: ```js run alert( `My\n`.length ); // 3 ``` -Note that `\n` is a single "special" character, so the length is indeed `3`. +Note que `\n` é um único carátere "especial", assim o comprimento é de facto `3`. -```warn header="`length` is a property" -People with a background in some other languages sometimes mistype by calling `str.length()` instead of just `str.length`. That doesn't work. +```warn header="`length` é uma propriedade" +Pessoas com conhecimento de outras linguagens por vezes erram ao invocar `str.length()` em vez de apenas `str.length`, o que não funciona. -Please note that `str.length` is a numeric property, not a function. There is no need to add parenthesis after it. -``` +Por favor, note que `str.length` é uma propriedade, não uma função. Não há necessidade de se adicionar parênteses depois dela. -## Accessing characters +## Acedendo aos carateres -To get a character at position `pos`, use square brackets `[pos]` or call the method [str.charAt(pos)](mdn:js/String/charAt). The first character starts from the zero position: +Para obter o carátere na posição `pos`, use parênteses retos ou invoque o método [str.charAt(pos)](mdn:js/String/charAt). O primeiro carátere começa na posição zero: ```js run -let str = `Hello`; - -// the first character -alert( str[0] ); // H -alert( str.charAt(0) ); // H +let str = `Olá`; -// the last character -alert( str[str.length - 1] ); // o +// o primeiro carátere +alert( str[0] ); // O +alert( str.charAt(0) ); // O +// o último carátere +alert( str[str.length - 1] ); // á ``` -The square brackets are a modern way of getting a character, while `charAt` exists mostly for historical reasons. +Os parênteses retos são uma forma moderna de se obter um carátere, enquanto `charAt` existe mais por razões históricas. -The only difference between them is that if no character is found, `[]` returns `undefined`, and `charAt` returns an empty string: +A única diferença entre eles está em que, se nenhum carátere for encontrado, `[]` retorna `undefined`, e `charAt` retorna uma *string* vazia (*empty string*): ```js run -let str = `Hello`; +let str = `Olá`; alert( str[1000] ); // undefined -alert( str.charAt(1000) ); // '' (an empty string) +alert( str.charAt(1000) ); // '' (uma string vazia) ``` -We can also iterate over characters using `for..of`: +Podemos também iterar sobre os carateres utilizando `for..of`: ```js run -for (let char of "Hello") { - alert(char); // H,e,l,l,o (char becomes "H", then "e", then "l" etc) +for (let char of "Olá") { + alert(char); // O,l,á (char se torna em "O", depois "l", etc) } ``` -## Strings are immutable +## *Strings* são imutáveis -Strings can't be changed in JavaScript. It is impossible to change a character. +As *strings* não podem ser alteradas em JavaScript. É impossível modificar um carátere. -Let's try it to show that it doesn't work: +Vamos tentar mostrar que isso não resulta: ```js run let str = 'Hi'; -str[0] = 'h'; // error -alert( str[0] ); // doesn't work +str[0] = 'h'; // erro +alert( str[0] ); // não resultou ``` -The usual workaround is to create a whole new string and assign it to `str` instead of the old one. +Uma solução alternativa comum é criar uma *string* completamente nova, e atribuí-la a `str` para substituir a velha. -For instance: +Por exemplo: ```js run let str = 'Hi'; -str = 'h' + str[1]; // replace the string +str = 'h' + str[1]; // substitui a string alert( str ); // hi ``` -In the following sections we'll see more examples of this. +Nas secções seguintes, veremos mais exemplos disto. -## Changing the case +## Alterando para maiúsculas/minúsculas -Methods [toLowerCase()](mdn:js/String/toLowerCase) and [toUpperCase()](mdn:js/String/toUpperCase) change the case: +Os métodos [toLowerCase()](mdn:js/String/toLowerCase) e [toUpperCase()](mdn:js/String/toUpperCase) mudam para maiúsculas/minúsculas (*case*): ```js run alert( 'Interface'.toUpperCase() ); // INTERFACE alert( 'Interface'.toLowerCase() ); // interface ``` -Or, if we want a single character lowercased: +Ou, se quiser um único carátere em minúsculas: ```js alert( 'Interface'[0].toLowerCase() ); // 'i' ``` -## Searching for a substring +## Procurando por uma *substring* -There are multiple ways to look for a substring within a string. +Existem múltiplas formas de procurar por uma *substring* dentro uma *string*. ### str.indexOf -The first method is [str.indexOf(substr, pos)](mdn:js/String/indexOf). +O primeiro método é [str.indexOf(substr, pos)](mdn:js/String/indexOf). -It looks for the `substr` in `str`, starting from the given position `pos`, and returns the position where the match was found or `-1` if nothing can be found. +Ele procura pela `substr` em `str`, começando por uma dada posição `pos`, e retorna a posição onde foi encontrada uma equivalência, ou `-1` se nada for encontrado. -For instance: +Por exemplo: ```js run -let str = 'Widget with id'; +let str = 'Widget com id'; -alert( str.indexOf('Widget') ); // 0, because 'Widget' is found at the beginning -alert( str.indexOf('widget') ); // -1, not found, the search is case-sensitive +alert( str.indexOf('Widget') ); // 0, porque 'Widget' é encontrado no principio +alert( str.indexOf('widget') ); // -1, não encontrado, a pesquisa é sensível a maiúsculas/minúsculas (case-sensitive) -alert( str.indexOf("id") ); // 1, "id" is found at the position 1 (..idget with id) +alert( str.indexOf("id") ); // 1, "id" é encontrado na posição 1 (..idget com id) ``` -The optional second parameter allows us to search starting from the given position. +O segundo parâmetro é opcional, e permite-nos começar a pesquisa a partir de uma dada posição. -For instance, the first occurrence of `"id"` is at position `1`. To look for the next occurrence, let's start the search from position `2`: +Por exemplo, a primeira ocorrência de `"id"` está na posição `1`. Para procurarmos pela segunda ocorrência, começemos a pesquisa pela posição `2`: ```js run -let str = 'Widget with id'; +let str = 'Widget com id'; -alert( str.indexOf('id', 2) ) // 12 +alert( str.indexOf('id', 2) ) // 11 ``` - -If we're interested in all occurrences, we can run `indexOf` in a loop. Every new call is made with the position after the previous match: +Se estivermos interessados em todas as ocorrências, podemos executar `indexOf` dentro de um laço (*loop*). Cada nova invocação é efetuada com a posição depois da equivalência anterior: ```js run -let str = 'As sly as a fox, as strong as an ox'; +let str = 'Tão manhosa como uma raposa, tão forte como um touro'; -let target = 'as'; // let's look for it +let target = 'como'; // vamos procurar or ela let pos = 0; while (true) { let foundPos = str.indexOf(target, pos); if (foundPos == -1) break; - alert( `Found at ${foundPos}` ); - pos = foundPos + 1; // continue the search from the next position + alert( `Encontrado em ${foundPos}` ); + pos = foundPos + 1; // continue a pesquisa a partir da próxima posição } ``` -The same algorithm can be layed out shorter: +O mesmo algoritmo pode ser colocado de uma forma mais curta: ```js run -let str = "As sly as a fox, as strong as an ox"; -let target = "as"; +let str = "Tão manhosa como uma raposa, tão forte como um touro"; +let target = "como"; *!* let pos = -1; @@ -276,232 +272,229 @@ while ((pos = str.indexOf(target, pos + 1)) != -1) { ``` ```smart header="`str.lastIndexOf(substr, position)`" -There is also a similar method [str.lastIndexOf(substr, position)](mdn:js/String/lastIndexOf) that searches from the end of a string to its beginning. +Também existe um método similar [str.lastIndexOf(substr, position)](mdn:js/String/lastIndexOf) que pesquisa do final para o início de uma string. -It would list the occurrences in the reverse order. +Ele listaria ocurrências na ordem invera. ``` -There is a slight inconvenience with `indexOf` in the `if` test. We can't put it in the `if` like this: +Há um ligeiro inconveniente com `indexOf` num teste `if`. Não o podemos utilizar num `if` desta forma: ```js run -let str = "Widget with id"; +let str = "Widget com id"; if (str.indexOf("Widget")) { - alert("We found it"); // doesn't work! + alert("Encontrámos"); // não funciona! } ``` -The `alert` in the example above doesn't show because `str.indexOf("Widget")` returns `0` (meaning that it found the match at the starting position). Right, but `if` considers `0` to be `false`. +O `alert` no exemplo acima não é mostrado porque `str.indexOf("Widget")` retorna `0` (o que significa que encontrou uma equivalência na posição inicial). Sim, mas `if` considera `0` como `false`. -So, we should actually check for `-1`, like this: +Assim, na verdade deveriamos verificar por `-1`, desta forma: ```js run -let str = "Widget with id"; +let str = "Widget com id"; *!* if (str.indexOf("Widget") != -1) { */!* - alert("We found it"); // works now! + alert("Encontrámos"); // funciona agora! } ``` -````smart header="The bitwise NOT trick" -One of the old tricks used here is the [bitwise NOT](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT) `~` operator. It converts the number to a 32-bit integer (removes the decimal part if exists) and then reverses all bits in its binary representation. +````smart header="O truque bitwise NOT" +Um dos velhos truques aqui utilizado é o operador `~` [bitwise NOT](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT). Ele converte o número para um inteiro de 32 bits (remove a parte decimal, se existir) e depois inverte todos os bits dessa representação binária. -For 32-bit integers the call `~n` means exactly the same as `-(n+1)` (due to IEEE-754 format). +Para inteiros de 32 bits, a invocação `~n` significa exatamente o mesmo que `-(n+1)` (devido ao formato IEEE-754). -For instance: +Por exemplo: ```js run -alert( ~2 ); // -3, the same as -(2+1) -alert( ~1 ); // -2, the same as -(1+1) -alert( ~0 ); // -1, the same as -(0+1) +alert( ~2 ); // -3, o mesmo que -(2+1) +alert( ~1 ); // -2, o mesmo que -(1+1) +alert( ~0 ); // -1, o mesmo que -(0+1) *!* -alert( ~-1 ); // 0, the same as -(-1+1) +alert( ~-1 ); // 0, o mesmo que -(-1+1) */!* ``` -As we can see, `~n` is zero only if `n == -1`. +Como vemos, `~n` é zero apenas se `n == -1`. -So, the test `if ( ~str.indexOf("...") )` is truthy that the result of `indexOf` is not `-1`. In other words, when there is a match. +Portanto, o teste `if ( ~str.indexOf("...") )` é verdadeiro (truthy) enquanto o resultado de `indexOf` não for `-1`. Por outras palavras, enquanto houver uma equivalência. -People use it to shorten `indexOf` checks: +As pessoas o utilizam para abreviar verificações com `indexOf`: ```js run let str = "Widget"; if (~str.indexOf("Widget")) { - alert( 'Found it!' ); // works + alert( 'Encontrada!' ); // funciona } ``` -It is usually not recommended to use language features in a non-obvious way, but this particular trick is widely used in old code, so we should understand it. +Geralmente, não é recomendado empregar funcionalidades da linguagem de uma forma não-óbvia, mas este truque em particular é amplamente utilizado em código antigo, assim deveríamos compreendê-lo. -Just remember: `if (~str.indexOf(...))` reads as "if found". +Apenas se lembre: `if (~str.indexOf(...))` se traduz como "se encontrado". ```` -### includes, startsWith, endsWith +### *includes*, *startsWith*, *endsWith* -The more modern method [str.includes(substr, pos)](mdn:js/String/includes) returns `true/false` depending on whether `str` contains `substr` within. +O método mais moderno [str.includes(substr, pos)](mdn:js/String/includes) retorna `true/false` dependendo de `str` conter a `substr` dentro. -It's the right choice if we need to test for the match, but don't need its position: +É a escolha certa se precisarmos de testar pela equivalência, mas não precisarmos da sua posição: ```js run -alert( "Widget with id".includes("Widget") ); // true +alert( "Widget com id".includes("Widget") ); // true (verdadeiro) -alert( "Hello".includes("Bye") ); // false +alert( "Hello".includes("Bye") ); // false (falso) ``` -The optional second argument of `str.includes` is the position to start searching from: +O opcional segundo argumento de `str.includes` é a posição para o início da pesquisa: ```js run -alert( "Widget".includes("id") ); // true -alert( "Widget".includes("id", 3) ); // false, from position 3 there is no "id" +alert( "Widget".includes("id") ); // true (verdadeiro) +alert( "Widget".includes("id", 3) ); // false (falso), a partir da posição 3 não existe "id" ``` -The methods [str.startsWith](mdn:js/String/startsWith) and [str.endsWith](mdn:js/String/endsWith) do exactly what they say: +Os métodos [str.startsWith](mdn:js/String/startsWith) e [str.endsWith](mdn:js/String/endsWith) fazem exatamente o que eles dizem: ```js run -alert( "Widget".startsWith("Wid") ); // true, "Widget" starts with "Wid" -alert( "Widget".endsWith("get") ); // true, "Widget" ends with "get" +alert( "Widget".startsWith("Wid") ); // true (verdadeiro), "Widget" começa com "Wid" +alert( "Widget".endsWith("get") ); // true (verdadeiro), "Widget" termina com "get" ``` -## Getting a substring +## Obtendo uma *substring* -There are 3 methods in JavaScript to get a substring: `substring`, `substr` and `slice`. +Existem 3 métodos em JavaScript para se obter uma *substring*: `substring`, `substr` e `slice`. `str.slice(start [, end])` -: Returns the part of the string from `start` to (but not including) `end`. +: Retorna a parte da *string* a partir de `start` até (mas não incluindo) `end`. - For instance: + Por exemplo: ```js run let str = "stringify"; - alert( str.slice(0, 5) ); // 'strin', the substring from 0 to 5 (not including 5) - alert( str.slice(0, 1) ); // 's', from 0 to 1, but not including 1, so only character at 0 + alert( str.slice(0, 5) ); // 'strin', a substring de 0 a 5 (não incluindo 5) + alert( str.slice(0, 1) ); // 's', de 0 a 1, mas não incluindo 1, portanto apenas o carátere em 0 ``` - If there is no second argument, then `slice` goes till the end of the string: + Se não houver um segundo argumento, então `slice` vai até ao final da *string*: ```js run let str = "st*!*ringify*/!*"; - alert( str.slice(2) ); // ringify, from the 2nd position till the end + alert( str.slice(2) ); // 'ringify', a partir da 2da posição até ao fim ``` - Negative values for `start/end` are also possible. They mean the position is counted from the string end: + Valores negativos para `start/end` também são possíveis. Eles significam que a posição é contada a partir do final da *string*: ```js run let str = "strin*!*gif*/!*y"; - // start at the 4th position from the right, end at the 1st from the right - alert( str.slice(-4, -1) ); // gif + // começa pela 4ta posição a contar pela direita, e termina na 1ra posição à direita + alert( str.slice(-4, -1) ); // 'gif' ``` - `str.substring(start [, end])` -: Returns the part of the string *between* `start` and `end`. +: Retorna a parte da string *entre* `start` e `end`. - This is almost the same as `slice`, but it allows `start` to be greater than `end`. + Este é quase o mesmo que `slice`, mas permite que `start` seja maior do que `end`. - For instance: + Por exemplo: ```js run let str = "st*!*ring*/!*ify"; - // these are same for substring + // estas significam o mesmo para substring alert( str.substring(2, 6) ); // "ring" alert( str.substring(6, 2) ); // "ring" - // ...but not for slice: - alert( str.slice(2, 6) ); // "ring" (the same) - alert( str.slice(6, 2) ); // "" (an empty string) - + // ...mas não para slice: + alert( str.slice(2, 6) ); // "ring" (o mesmo) + alert( str.slice(6, 2) ); // "" (uma string vazia) ``` - Negative arguments are (unlike slice) not supported, they are treated as `0`. + Argumentos negativos (ao contrário de slice) não são suportados, eles são tratados como `0`. `str.substr(start [, length])` -: Returns the part of the string from `start`, with the given `length`. +: Retorna a parte da *string* a começar por `start`, com o dado comprimento `length`. - In contrast with the previous methods, this one allows us to specify the `length` instead of the ending position: + Em contraste com os métodos anteriores, este permite-nos especificar `length` (o comprimento) em vez da posição final: ```js run let str = "st*!*ring*/!*ify"; - alert( str.substr(2, 4) ); // ring, from the 2nd position get 4 characters + alert( str.substr(2, 4) ); // 'ring', a partir da 2da posição obtenha 4 carateres ``` - The first argument may be negative, to count from the end: + O primeiro argumento pode ser negativo, para a contagem a partir do fim: ```js run let str = "strin*!*gi*/!*fy"; - alert( str.substr(-4, 2) ); // gi, from the 4th position get 2 characters + alert( str.substr(-4, 2) ); // 'gi', a partir da 4ta posição otenha 2 carateres ``` -Let's recap these methods to avoid any confusion: +Vamos recapitular estes métodos afim de evitarmos qualquer confusão: -| method | selects... | negatives | +| método | seleciona... | negativos | |--------|-----------|-----------| -| `slice(start, end)` | from `start` to `end` (not including `end`) | allows negatives | -| `substring(start, end)` | between `start` and `end` | negative values mean `0` | -| `substr(start, length)` | from `start` get `length` characters | allows negative `start` | +| `slice(start, end)` | de `start` para `end` (não incluindo `end`) | permite negativos | +| `substring(start, end)` | entre `start` e `end` | valores negativos significam `0` | +| `substr(start, length)` | de `start` obtenha `length` carateres | permite `start` negativo| +```smart header="Qual escolher?" +Todos eles executam o trabalho. Formalmente, `substr` tem uma pequena desvantagem: não está descrito na especificação nuclear de JavaScript, mas no Annex B, que cobre funcionalidades apenas para navegadores (browser-only) que existam principalmente por razões históricas. Assim, ambientes não para navegadores podem não o suportar. Mas, na prática funciona em qualquer lugar. -```smart header="Which one to choose?" -All of them can do the job. Formally, `substr` has a minor drawback: it is described not in the core JavaScript specification, but in Annex B, which covers browser-only features that exist mainly for historical reasons. So, non-browser environments may fail to support it. But in practice it works everywhere. - -The author finds themself using `slice` almost all the time. +O autor vê-se a utilizar `slice` quase pelo tempo todo. ``` -## Comparing strings +## Comparando *strings* -As we know from the chapter , strings are compared character-by-character in alphabetical order. +Como sabemos pelo capítulo , *strings* são comparadas carátere-por-carátere por ordem alfabética. -Although, there are some oddities. +Contudo, existem algumas particularidades. -1. A lowercase letter is always greater than the uppercase: +1. Uma letra em minúsculas é sempre maior do que uma em maiúsculas: ```js run - alert( 'a' > 'Z' ); // true + alert( 'a' > 'Z' ); // true (verdadeiro) ``` -2. Letters with diacritical marks are "out of order": +2. Letras com marcas diacríticas estão "fora da ordem": ```js run - alert( 'Österreich' > 'Zealand' ); // true + alert( 'Österreich' > 'Zealand' ); // true (verdadeiro) ``` - This may lead to strange results if we sort these country names. Usually people would expect `Zealand` to come after `Österreich` in the list. + Isto pode levar a resultados estranhos se ordenarmos estes países por nome. Habitualmente, as pessoas esperam que `Zealand` venha depois de `Österreich` numa lista. -To understand what happens, let's review the internal representation of strings in JavaScript. +Para se compreender o que acontece, vamos rever a representação interna das *strings* em JavaScript. -All strings are encoded using [UTF-16](https://en.wikipedia.org/wiki/UTF-16). That is: each character has a corresponding numeric code. There are special methods that allow to get the character for the code and back. +Todas as *strings* são codificadas empregando [UTF-16](https://en.wikipedia.org/wiki/UTF-16). Isto é: cada carátere corresponde a um código numérico. Existem métodos especiais que permitem obter o carátere a partir do código, e vice-versa. `str.codePointAt(pos)` -: Returns the code for the character at position `pos`: +: Retorna o código para o carátere na posição `pos`: - ```js run - // different case letters have different codes + ```js run + // letras minúsculas e maiúsculas têm códigos diferentes alert( "z".codePointAt(0) ); // 122 alert( "Z".codePointAt(0) ); // 90 - ``` + ``` `String.fromCodePoint(code)` -: Creates a character by its numeric `code` +: Cria um carátere a partir do seu código numérico (`code`) - ```js run + ```js run alert( String.fromCodePoint(90) ); // Z - ``` + ``` - We can also add unicode characters by their codes using `\u` followed by the hex code: + Podemos também adicionar carateres *unicode* por intermédio dos seus códigos empregando `\u` seguido pelo seu código hexadecimal: ```js run - // 90 is 5a in hexadecimal system + // 90 é 5a no sistema hexadecimal alert( '\u005a' ); // Z ``` -Now let's see the characters with codes `65..220` (the latin alphabet and a little bit extra) by making a string of them: +Agora, vamos ver os carateres com os códigos `65..220` (o alfabeto latino e um pouco mais extra), formando uma *string* com eles: ```js run let str = ''; @@ -514,161 +507,160 @@ alert( str ); // ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜ ``` -See? Capital characters go first, then a few special ones, then lowercase characters. - -Now it becomes obvious why `a > Z`. +Vê? Carateres maiúsculos vêm primeiro, depois uns poucos especiais, e a seguir carateres minúsculos. -The characters are compared by their numeric code. The greater code means that the character is greater. The code for `a` (97) is greater than the code for `Z` (90). +Portanto, torna-se óbvio porque `a > Z`. -- All lowercase letters go after uppercase letters because their codes are greater. -- Some letters like `Ö` stand apart from the main alphabet. Here, it's code is greater than anything from `a` to `z`. +Os carateres são comparados por intermédio do seu código numérico. Quanto maior o código maior será o carátere. O código para `a` (97) é maior do que o código para `Z` (90). +- Todas as letras em minúsculas vêm depois das letras em maiúsculas porque os seus códigos são maiores. +- Algumas letras como `Ö` estão separadas do alfabeto principal. Aqui, o seu código é maior do que qualquer um de `a` a `z`. -### Correct comparisons +### Comparações corretas -The "right" algorithm to do string comparisons is more complex than it may seem, because alphabets are different for different languages. The same-looking letter may be located differently in different alphabets. +O algoritmo "correto" para efetuar comparações de *strings* é mais complexo do que parece, porque alfabetos são diferentes em diferentes línguas. Uma letra com o mesmo aspeto pode ter localizações diferentes em diferentes alfabetos. -So, the browser needs to know the language to compare. +Assim, o navegador (*browser*) precisa de saber a língua para efetuar a comparação. -Luckily, all modern browsers (IE10- requires the additional library [Intl.JS](https://github.com/andyearnshaw/Intl.js/)) support the internationalization standard [ECMA 402](http://www.ecma-international.org/ecma-402/1.0/ECMA-402.pdf). +Felizmente, todos os navegadores modernos (IE10- requrem uma biblioteca [Intl.JS](https://github.com/andyearnshaw/Intl.js/) adicional) suportam a internacionalização padrão [ECMA 402](http://www.ecma-international.org/ecma-402/1.0/ECMA-402.pdf). -It provides a special method to compare strings in different languages, following their rules. +Ela fornece um método especial para comparar *strings* em línguas diferentes, seguindo as suas regras. -The call [str.localeCompare(str2)](mdn:js/String/localeCompare): +A invocação [str.localeCompare(str2)](mdn:js/String/localeCompare): -- Returns `1` if `str` is greater than `str2` according to the language rules. -- Returns `-1` if `str` is less than `str2`. -- Returns `0` if they are equal. +- Retorna `1`, se `str` é maior do que `str2`, de acordo com as regras da língua. +- Retorna `-1`, se `str` é menor do que `str2`. +- Retorna `0`, se forem iguais. -For instance: +Por exemplo: ```js run alert( 'Österreich'.localeCompare('Zealand') ); // -1 ``` -This method actually has two additional arguments specified in [the documentation](mdn:js/String/localeCompare), which allows it to specify the language (by default taken from the environment) and setup additional rules like case sensitivity or should `"a"` and `"á"` be treated as the same etc. +Na verdade, este método tem dois argumentos adicionais especificados em [the documentation](mdn:js/String/localeCompare), que permitem especificar a língua (por defeito, tomada do ambiente local), e configurar regras adicionais como sensibilidade a maiúsculas/minúsculas (*case-sensitivity*) ou se deveriam `"a"` e `"á"` ser tratados como o mesmo, etc. -## Internals, Unicode +## Internamente, *Unicode* -```warn header="Advanced knowledge" -The section goes deeper into string internals. This knowledge will be useful for you if you plan to deal with emoji, rare mathematical or hieroglyphic characters or other rare symbols. +```warn header="Conhecimento avançado" +A secção aprofunda o funcionamento interno da string. Este conhecimento lhe será útil se planear lidar com emoji, carateres matemáticos raros, hieróglifos, ou outros símbolos raros. -You can skip the section if you don't plan to support them. +Pode saltar esta secção se não planear suportá-los. ``` -### Surrogate pairs +### *Pares substitutos* -Most symbols have a 2-byte code. Letters in most european languages, numbers, and even most hieroglyphs, have a 2-byte representation. +Muitos símbolos têm um código de 2-bytes. Letras em muitas línguas europeias, números, e mesmo muitos hieróglifos, têm uma representação em 2-bytes. -But 2 bytes only allow 65536 combinations and that's not enough for every possible symbol. So rare symbols are encoded with a pair of 2-byte characters called "a surrogate pair". +Mas, 2 bytes apenas permitem 65536 combinações, o que não é suficiente para todos os símbolos possíveis. Assim, símbolos raros são codificados com um par de carateres de 2-bytes chamado de "par substituto" (*surrogate pair*). -The length of such symbols is `2`: +O comprimento de tais símbolos é `2`: ```js run -alert( '𝒳'.length ); // 2, MATHEMATICAL SCRIPT CAPITAL X -alert( '😂'.length ); // 2, FACE WITH TEARS OF JOY -alert( '𩷶'.length ); // 2, a rare chinese hieroglyph +alert( '𝒳'.length ); // 2, símbolo matemático X maiúsculo +alert( '😂'.length ); // 2, face com lágrimas de alegria +alert( '𩷶'.length ); // 2, um raro hieróglifo chinês ``` -Note that surrogate pairs did not exist at the time when JavaScript was created, and thus are not correctly processed by the language! +Note que pares substitutos não existiam quando JavaScript foi criada, e desta forma não são corretamente processados pela linguagem! -We actually have a single symbol in each of the strings above, but the `length` shows a length of `2`. +Na verdade, temos um único símbolo em cada uma das *strings* acima, mas `length` mostra um comprimento de `2`. -`String.fromCodePoint` and `str.codePointAt` are few rare methods that deal with surrogate pairs right. They recently appeared in the language. Before them, there were only [String.fromCharCode](mdn:js/String/fromCharCode) and [str.charCodeAt](mdn:js/String/charCodeAt). These methods are actually the same as `fromCodePoint/codePointAt`, but don't work with surrogate pairs. +`String.fromCodePoint` e `str.codePointAt` são dos poucos raros métodos que lidam bem com pares substitutos (*surrogate pairs*). Eles apareceram recentemente na linguagem. Antes deles, apenas existiam [String.fromCharCode](mdn:js/String/fromCharCode) e [str.charCodeAt](mdn:js/String/charCodeAt). Estes métodos são na verdade o mesmo que `fromCodePoint/codePointAt`, mas não trabalham com pares substitutos. -But, for instance, getting a symbol can be tricky, because surrogate pairs are treated as two characters: +Contudo, por exemplo, para se obter um símbolo pode ser complicado, porque pares substitutos são tratados como dois carateres: ```js run -alert( '𝒳'[0] ); // strange symbols... -alert( '𝒳'[1] ); // ...pieces of the surrogate pair +alert( '𝒳'[0] ); // símbolos estranhos... +alert( '𝒳'[1] ); // ...partes do par substituto ``` -Note that pieces of the surrogate pair have no meaning without each other. So the alerts in the example above actually display garbage. +Note que partes do par substituto não têm nenhum significado, a não ser que formem um todo. Assim os *alerts* no exemplo acima, na verdade, mostram lixo. -Technically, surrogate pairs are also detectable by their codes: if a character has the code in the interval of `0xd800..0xdbff`, then it is the first part of the surrogate pair. The next character (second part) must have the code in interval `0xdc00..0xdfff`. These intervals are reserved exclusively for surrogate pairs by the standard. +Tecnicamente, pares substitutos também são detetáveis pelo seus códigos: se um carátere tiver o código no intervalo `0xd800..0xdbff`, então é a primeira parte de um par substituto. O carátere seguinte (a segunda parte) deve ter o código no intervalo `0xdc00..0xdfff`. Estes intervalos estão exclusivamente reservados a pares substitutos pela especificação. -In the case above: +No caso acima: ```js run -// charCodeAt is not surrogate-pair aware, so it gives codes for parts +// charCodeAt não suporta pares substitutos, assim fornece códigos para as partes -alert( '𝒳'.charCodeAt(0).toString(16) ); // d835, between 0xd800 and 0xdbff -alert( '𝒳'.charCodeAt(1).toString(16) ); // dcb3, between 0xdc00 and 0xdfff +alert( '𝒳'.charCodeAt(0).toString(16) ); // d835, entre 0xd800 e 0xdbff +alert( '𝒳'.charCodeAt(1).toString(16) ); // dcb3, entre 0xdc00 e 0xdfff ``` -You will find more ways to deal with surrogate pairs later in the chapter . There are probably special libraries for that too, but nothing famous enough to suggest here. +Encontrará mais formas para lidar com pares substitutos mais adiante no capítulo + . Provavelmente, também existem bibliotecas (*libraries*) especiais para isso, mas nada suficientemente famoso para sugestão aqui. -### Diacritical marks and normalization +### Marcas diacríticas e normalização -In many languages there are symbols that are composed of the base character with a mark above/under it. +Em muitas línguas, existem símbolos que são compostos por um carátere base com uma marca acima/abaixo dele. -For instance, the letter `a` can be the base character for: `àáâäãåā`. Most common "composite" character have their own code in the UTF-16 table. But not all of them, because there are too many possible combinations. +Por exemplo, a letra `a` pode ser o carátere base para: `àáâäãåā`. Os mais comuns carateres "compostos" têm os seus próprios códigos na tabela UTF-16. Mas não todos, porque existem demasiadas combinações possíveis. -To support arbitrary compositions, UTF-16 allows us to use several unicode characters. The base character and one or many "mark" characters that "decorate" it. +Para suportar composições arbitrárias, UTF-16 permite-nos utilizar múltiplos carateres *unicode*. O carátere base e, um ou muitos, carateres "marca" que o "decorem". -For instance, if we have `S` followed by the special "dot above" character (code `\u0307`), it is shown as Ṡ. +Por exemplo, se tivermos `S` seguido pelo carátere especial "ponto superior" (código `\u0307`), é mostrado como Ṡ. ```js run alert( 'S\u0307' ); // Ṡ ``` -If we need an additional mark above the letter (or below it) -- no problem, just add the necessary mark character. +Se, precisarmos de uma marca adicional acima da letra (ou abaixo dela) -- não há problema, apenas adicionamos o necessário carátere marca. -For instance, if we append a character "dot below" (code `\u0323`), then we'll have "S with dots above and below": `Ṩ`. +Por exemplo, se acrescentarmos um carátere "ponto abaixo" (código `\u0323`), então teremos "S com pontos acima e abaixo": `Ṩ`. -For example: +Por exemplo: ```js run alert( 'S\u0307\u0323' ); // Ṩ ``` -This provides great flexibility, but also an interesting problem: two characters may visually look the same, but be represented with different unicode compositions. +Isto provê grande flexibilidade, mas também um problema interessante: dois carateres podem visualmente parecer semelhantes, mas estar representados por composições *unicode* diferentes. -For instance: +Por exemplo: ```js run -alert( 'S\u0307\u0323' ); // Ṩ, S + dot above + dot below -alert( 'S\u0323\u0307' ); // Ṩ, S + dot below + dot above +alert( 'S\u0307\u0323' ); // Ṩ, S + ponto acima + ponto abaixo +alert( 'S\u0323\u0307' ); // Ṩ, S + ponto abaixo + ponto acima -alert( 'S\u0307\u0323' == 'S\u0323\u0307' ); // false +alert( 'S\u0307\u0323' == 'S\u0323\u0307' ); // false (falso) ``` -To solve this, there exists a "unicode normalization" algorithm that brings each string to the single "normal" form. +Para solucionar isto, existe um algoritmo para "normalização *unicode*" que leva cada *string* a uma única forma "normal". -It is implemented by [str.normalize()](mdn:js/String/normalize). +Ele é implementado por [str.normalize()](mdn:js/String/normalize). ```js run -alert( "S\u0307\u0323".normalize() == "S\u0323\u0307".normalize() ); // true +alert( "S\u0307\u0323".normalize() == "S\u0323\u0307".normalize() ); // true (verdadeiro) ``` -It's funny that in our situation `normalize()` actually brings together a sequence of 3 characters to one: `\u1e68` (S with two dots). +É engraçado que na nossa situação `normalize()` leve, na realidade, a sequência de 3 carateres para um: `\u1e68` (S com dois pontos). ```js run alert( "S\u0307\u0323".normalize().length ); // 1 -alert( "S\u0307\u0323".normalize() == "\u1e68" ); // true +alert( "S\u0307\u0323".normalize() == "\u1e68" ); // true (verdadeiro) ``` -In reality, this is not always the case. The reason being that the symbol `Ṩ` is "common enough", so UTF-16 creators included it in the main table and gave it the code. - -If you want to learn more about normalization rules and variants -- they are described in the appendix of the Unicode standard: [Unicode Normalization Forms](http://www.unicode.org/reports/tr15/), but for most practical purposes the information from this section is enough. +Na realidade, nem sempre é o caso. A razão para o acima reside no facto de `Ṩ` ser "suficientemente comum", e por isso os criadores do UTF-16 o incluiram na tabela principal e o deram um código. +Se quiser aprender mais sobre regras e variantes de normalização -- elas são descritas no apêndice do padrão Unicode: [Unicode Normalization Forms](http://www.unicode.org/reports/tr15/), mas para a maioria dos propósitos práticos a informação nesta secção é suficiente. -## Summary +## Sumário -- There are 3 types of quotes. Backticks allow a string to span multiple lines and embed expressions. -- Strings in JavaScript are encoded using UTF-16. -- We can use special characters like `\n` and insert letters by their unicode using `\u...`. -- To get a character, use: `[]`. -- To get a substring, use: `slice` or `substring`. -- To lowercase/uppercase a string, use: `toLowerCase/toUpperCase`. -- To look for a substring, use: `indexOf`, or `includes/startsWith/endsWith` for simple checks. -- To compare strings according to the language, use: `localeCompare`, otherwise they are compared by character codes. +- Existem 3 tipos de aspas. *Backticks* permitem expressões embebidas, e que uma *string* se estenda por múltiplas linhas. +- As *Strings* em JavaScript são codificadas empregando UTF-16. +- Podemos utilizar carateres especiais como `\n`, e inserir letras por intermédio do seu *unicode* utilizando `\u...`. +- Para obter um carátere, use: `[]`. +- Para obter uma *substring*, use: `slice` ou `substring`. +- Para tornar uma *string* em minúsculas/maiúsculas, use: `toLowerCase/toUpperCase`. +- Para procurar por uma *substring*, use: `indexOf`, ou `includes/startsWith/endsWith` para simples verificações. +- Para comparar *strings* de acordo com a língua, use: `localeCompare`, de contrário elas são comparadas pelos códigos dos carateres. -There are several other helpful methods in strings: +Existem vários outros métodos úteis para *strings*: -- `str.trim()` -- removes ("trims") spaces from the beginning and end of the string. -- `str.repeat(n)` -- repeats the string `n` times. -- ...and more. See the [manual](mdn:js/String) for details. +- `str.trim()` -- remove ("*trims*") espaços do inicio e final da *string*. +- `str.repeat(n)` -- repete a *string* `n` vezes. +- ...e mais. Veja o [manual](mdn:js/String) para detalhes. -Strings also have methods for doing search/replace with regular expressions. But that topic deserves a separate chapter, so we'll return to that later. +As *strings* também possuem métodos para se efetuar a procura/substituição com expressões regulares (*regular expressions*). Mas, este tópico merece um capítulo em separado, e por isso voltaremos a ele mais adiante.