diff --git a/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js b/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js index 490f570ad..00bcc78e9 100644 --- a/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/1-camelcase/_js.view/solution.js @@ -1,10 +1,10 @@ function camelize(str) { return str - .split('-') // splits 'my-long-word' into array ['my', 'long', 'word'] + .split('-') // separa 'my-long-word' em um array ['my', 'long', 'word'] .map( - // capitalizes first letters of all array items except the first one - // converts ['my', 'long', 'word'] into ['my', 'Long', 'Word'] + // deixa as primeiras letras de todos os itens do array em maiúsculo exceto o primeiro item + // converte ['my', 'long', 'word'] em ['my', 'Long', 'Word'] (word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1) ) - .join(''); // joins ['my', 'Long', 'Word'] into 'myLongWord' + .join(''); // une ['my', 'Long', 'Word'] formando 'myLongWord' } diff --git a/1-js/05-data-types/05-array-methods/1-camelcase/task.md b/1-js/05-data-types/05-array-methods/1-camelcase/task.md index ef5944636..fdd3e5161 100644 --- a/1-js/05-data-types/05-array-methods/1-camelcase/task.md +++ b/1-js/05-data-types/05-array-methods/1-camelcase/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Translate border-left-width to borderLeftWidth +# Mude border-left-width para borderLeftWidth -Write the function `camelize(str)` that changes dash-separated words like "my-short-string" into camel-cased "myShortString". +Escreva uma função `camelize(str)` que mude as palavras separadas por traços como "my-short-string" para palavras em camelCase "myShortString". -That is: removes all dashes, each word after dash becomes uppercased. +Ou seja: remova todos os traços, cada palavra depois do traço precisa estar em maiúsculo. -Examples: +Exemplos: ```js camelize("background-color") == 'backgroundColor'; @@ -16,4 +16,4 @@ camelize("list-style-image") == 'listStyleImage'; camelize("-webkit-transition") == 'WebkitTransition'; ``` -P.S. Hint: use `split` to split the string into an array, transform it and `join` back. +P.S. Dica: use `split` para separar a string em um array, transforme-os e os junte de volta usando `join`. diff --git a/1-js/05-data-types/05-array-methods/10-average-age/task.md b/1-js/05-data-types/05-array-methods/10-average-age/task.md index a991c156b..be9902dbc 100644 --- a/1-js/05-data-types/05-array-methods/10-average-age/task.md +++ b/1-js/05-data-types/05-array-methods/10-average-age/task.md @@ -2,13 +2,13 @@ importance: 4 --- -# Get average age +# Pegar a média de idade -Write the function `getAverageAge(users)` that gets an array of objects with property `age` and gets the average. +Escreva a função `getAverageAge(users)` que recebe um array de objetos com a propriedade `age` e pega a média entre eles. -The formula for the average is `(age1 + age2 + ... + ageN) / N`. +A fórmula da média é `(age1 + age2 + ... + ageN) / N`. -For instance: +Por exemplo: ```js no-beautify let john = { name: "John", age: 25 }; diff --git a/1-js/05-data-types/05-array-methods/11-array-unique/solution.md b/1-js/05-data-types/05-array-methods/11-array-unique/solution.md index 32d3b2679..6dd881bcc 100644 --- a/1-js/05-data-types/05-array-methods/11-array-unique/solution.md +++ b/1-js/05-data-types/05-array-methods/11-array-unique/solution.md @@ -1,6 +1,6 @@ -Let's walk the array items: -- For each item we'll check if the resulting array already has that item. -- If it is so, then ignore, otherwise add to results. +Vamos percorrer os itens do array: +- Para cada item, vamos checar se o array `result` já possui esse item. +- Se sim, então será ignorado, do contrário será adicionado a `result`. ```js run demo function unique(arr) { @@ -22,18 +22,18 @@ let strings = ["Hare", "Krishna", "Hare", "Krishna", alert( unique(strings) ); // Hare, Krishna, :-O ``` -The code works, but there's a potential performance problem in it. +O código funciona, porém existe um potencial problema de performance aqui. -The method `result.includes(str)` internally walks the array `result` and compares each element against `str` to find the match. +O método `result.includes(str)` internamente percorre o array `result` e compara cada elemento com `str` para achar um que combine. -So if there are `100` elements in `result` and no one matches `str`, then it will walk the whole `result` and do exactly `100` comparisons. And if `result` is large, like `10000`, then there would be `10000` comparisons. +Então se tiver `100` elementos em `result` e nenhum combine com `str`, então ele vai percorrer `result` inteiro e fazer exatamente `100` comparações. E se `result` for muito maior, como `10000`, então terá `10000` comparações. -That's not a problem by itself, because JavaScript engines are very fast, so walk `10000` array is a matter of microseconds. +Isso não é um problema tão preocupante porque as engines do JavaScript são muito rápidas, então percorrer um array de `10000` itens dura questões de microsegundos. -But we do such test for each element of `arr`, in the `for` loop. +Porém, nós estamos fazendo estes teste para cada elemento em `arr` no laço de repetição `for`. -So if `arr.length` is `10000` we'll have something like `10000*10000` = 100 millions of comparisons. That's a lot. +Então se `arr.length` for `10000` vamos ter algo como: `10000*10000` = 100 milhões de comparações. Isso é muito. -So the solution is only good for small arrays. +Então, essa solução é somente boa para arrays pequenas. -Further in the chapter we'll see how to optimize it. +Mais adiante no capítulo vamos ver como otimizar isso. diff --git a/1-js/05-data-types/05-array-methods/11-array-unique/task.md b/1-js/05-data-types/05-array-methods/11-array-unique/task.md index 5b56d3621..fba54e650 100644 --- a/1-js/05-data-types/05-array-methods/11-array-unique/task.md +++ b/1-js/05-data-types/05-array-methods/11-array-unique/task.md @@ -2,17 +2,17 @@ importance: 4 --- -# Filter unique array members +# Filtre membros únicos de um array -Let `arr` be an array. +Deixe `arr` ser um array. -Create a function `unique(arr)` that should return an array with unique items of `arr`. +Crie a função `unique(arr)` que recebe um array `string` e retorna outro array `arr` com itens únicos/que mais se repetem do array recebido. -For instance: +Por exemplo: ```js function unique(arr) { - /* your code */ + /* seu código */ } let strings = ["Hare", "Krishna", "Hare", "Krishna", diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js b/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js index 0bdfbae5a..2a82ac377 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/2-filter-range/_js.view/solution.js @@ -1,5 +1,5 @@ function filterRange(arr, a, b) { - // added brackets around the expression for better readability + // colchetes adicionado ao redor da expressão para melhor entendimento return arr.filter(item => (a <= item && item <= b)); } \ No newline at end of file diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/solution.md b/1-js/05-data-types/05-array-methods/2-filter-range/solution.md index 73993a07a..39c83cfc7 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/solution.md +++ b/1-js/05-data-types/05-array-methods/2-filter-range/solution.md @@ -1,6 +1,6 @@ ```js run demo function filterRange(arr, a, b) { - // added brackets around the expression for better readability + // colchetes adicionado ao redor da expressão para melhor entendimento return arr.filter(item => (a <= item && item <= b)); } @@ -8,7 +8,7 @@ let arr = [5, 3, 8, 1]; let filtered = filterRange(arr, 1, 4); -alert( filtered ); // 3,1 (matching values) +alert( filtered ); // 3,1 (valores que coincidem com o que foi pedido) -alert( arr ); // 5,3,8,1 (not modified) +alert( arr ); // 5,3,8,1 (array não foi modificada) ``` diff --git a/1-js/05-data-types/05-array-methods/2-filter-range/task.md b/1-js/05-data-types/05-array-methods/2-filter-range/task.md index 18b2c1d9b..b4068f0aa 100644 --- a/1-js/05-data-types/05-array-methods/2-filter-range/task.md +++ b/1-js/05-data-types/05-array-methods/2-filter-range/task.md @@ -4,19 +4,19 @@ importance: 4 # Filter range -Write a function `filterRange(arr, a, b)` that gets an array `arr`, looks for elements between `a` and `b` in it and returns an array of them. +Escreva uma função `filterRange(arr, a, b)` que pegue um array `arr`, procure por elementos entre `a` e `b` e retorne um array novo com os elementos encontrados. -The function should not modify the array. It should return the new array. +A função não deve modificar o array. Deve retornar um novo array. -For instance: +Exemplo: ```js let arr = [5, 3, 8, 1]; let filtered = filterRange(arr, 1, 4); -alert( filtered ); // 3,1 (matching values) +alert( filtered ); // 3,1 (valores que coincidem com o que foi pedido) -alert( arr ); // 5,3,8,1 (not modified) +alert( arr ); // 5,3,8,1 (array não foi modificada) ``` diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js index 488db3755..f9af1a4f3 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/_js.view/solution.js @@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) { for (let i = 0; i < arr.length; i++) { let val = arr[i]; - // remove if outside of the interval + //remove se estiver fora do intervalo if (val < a || val > b) { arr.splice(i, 1); i--; diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md index 36e3130ff..9301242ea 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/solution.md @@ -4,7 +4,7 @@ function filterRangeInPlace(arr, a, b) { for (let i = 0; i < arr.length; i++) { let val = arr[i]; - // remove if outside of the interval + //remove se estiver fora do intervalo if (val < a || val > b) { arr.splice(i, 1); i--; @@ -15,7 +15,7 @@ function filterRangeInPlace(arr, a, b) { let arr = [5, 3, 8, 1]; -filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4 +filterRangeInPlace(arr, 1, 4); // remove os números exceto números de 1 á 4 alert( arr ); // [3, 1] ``` diff --git a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md index 7066a51ab..86008af7f 100644 --- a/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md +++ b/1-js/05-data-types/05-array-methods/3-filter-range-in-place/task.md @@ -4,15 +4,15 @@ importance: 4 # Filter range "in place" -Write a function `filterRangeInPlace(arr, a, b)` that gets an array `arr` and removes from it all values except those that are between `a` and `b`. The test is: `a ≤ arr[i] ≤ b`. +Escreva uma função `filterRangeInPlace(arr, a, b)` que pegue um array `arr` e remova dele todos os valores exceto aqueles que estão entre `a` e `b`. A condição é: `a ≤ arr[i] ≤ b`. -The function should only modify the array. It should not return anything. +A função deve modificar a array. Não deve retornar um valor. -For instance: +Exemplo: ```js let arr = [5, 3, 8, 1]; -filterRangeInPlace(arr, 1, 4); // removed the numbers except from 1 to 4 +filterRangeInPlace(arr, 1, 4); // remove os números exceto números de 1 á 4 alert( arr ); // [3, 1] ``` diff --git a/1-js/05-data-types/05-array-methods/4-sort-back/task.md b/1-js/05-data-types/05-array-methods/4-sort-back/task.md index 05a08aad0..d6234efa8 100644 --- a/1-js/05-data-types/05-array-methods/4-sort-back/task.md +++ b/1-js/05-data-types/05-array-methods/4-sort-back/task.md @@ -2,12 +2,12 @@ importance: 4 --- -# Sort in the reverse order +# Ordene (sort) na ordem decrescente ```js let arr = [5, 2, 1, -10, 8]; -// ... your code to sort it in the reverse order +// ... seu código para ordenar na ordem decrescente alert( arr ); // 8, 5, 2, 1, -10 ``` diff --git a/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md b/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md index 8537b129e..2f05fe24e 100644 --- a/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md +++ b/1-js/05-data-types/05-array-methods/5-copy-sort-array/solution.md @@ -1,4 +1,4 @@ -We can use `slice()` to make a copy and run the sort on it: +Podemos usar `slice()` para fazer a cópia e executar o método `sort()` logo depois: ```js run function copySorted(arr) { diff --git a/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md b/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md index c1395b4ad..b12e76704 100644 --- a/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md +++ b/1-js/05-data-types/05-array-methods/5-copy-sort-array/task.md @@ -2,11 +2,11 @@ importance: 5 --- -# Copy and sort array +# Copie e ordene o array -We have an array of strings `arr`. We'd like to have a sorted copy of it, but keep `arr` unmodified. +Temos um array de strings `arr`. Gostaríamos de ter uma copia ordenada desse array, porém mantenha `arr` do mesmo jeito, sem modificações. -Create a function `copySorted(arr)` that returns such a copy. +Crie uma função `copySorted(arr)` que retorna a copia. ```js let arr = ["HTML", "JavaScript", "CSS"]; @@ -14,5 +14,5 @@ let arr = ["HTML", "JavaScript", "CSS"]; let sorted = copySorted(arr); alert( sorted ); // CSS, HTML, JavaScript -alert( arr ); // HTML, JavaScript, CSS (no changes) +alert( arr ); // HTML, JavaScript, CSS (arr sem alterções) ``` diff --git a/1-js/05-data-types/05-array-methods/6-array-get-names/task.md b/1-js/05-data-types/05-array-methods/6-array-get-names/task.md index 74c8a9d74..a5c9c0b51 100644 --- a/1-js/05-data-types/05-array-methods/6-array-get-names/task.md +++ b/1-js/05-data-types/05-array-methods/6-array-get-names/task.md @@ -2,11 +2,11 @@ importance: 5 --- -# Map to names +# Map para nomes -You have an array of `user` objects, each one has `user.name`. Write the code that converts it into an array of names. +Você tem um array de objetos `user`, cada um possui `user.name`. Escreva um código que converta o array para um array de nomes. -For instance: +Exemplo: ```js no-beautify let john = { name: "John", age: 25 }; @@ -15,7 +15,7 @@ let mary = { name: "Mary", age: 28 }; let users = [ john, pete, mary ]; -let names = /* ... your code */ +let names = /* ... seu código */ alert( names ); // John, Pete, Mary ``` diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md b/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md index 41178663d..b8c02d903 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/solution.md @@ -1,3 +1,3 @@ -- Please note how methods are stored. They are simply added to the internal object. -- All tests and numeric conversions are done in the `calculate` method. In future it may be extended to support more complex expressions. +- Por favor, note como os métodos são armazenados. Eles são simplesmente adicionados no objeto interno. +- Todos os testes e conversões numéricas são feitas no método `calculate`. No futuro, pode ser extendida para suportar mais expressões complexas. diff --git a/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md b/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md index cc5453ceb..806cec91e 100644 --- a/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md +++ b/1-js/05-data-types/05-array-methods/6-calculator-extendable/task.md @@ -2,35 +2,38 @@ importance: 5 --- -# Create an extendable calculator +# Crie uma calculadora extensível -Create a constructor function `Calculator` that creates "extendable" calculator objects. +Construa uma função construtora `Calculator` que crie objetos de calculadora "extensível". -The task consists of two parts. +A atividade consiste de duas partes. -1. First, implement the method `calculate(str)` that takes a string like `"1 + 2"` in the format "NUMBER operator NUMBER" (space-delimited) and returns the result. Should understand plus `+` and minus `-`. +1. Primeiro, implemente o método `calculate(str)` que pegue uma string como `"1 + 2"` e a deixe no formato "NÚMERO operador NÚMERO" (delimitada por espaços) e retorne o resultado. Deve entender os operadores mais `+` e menos `-`. - Usage example: + Exemplo: ```js let calc = new Calculator; alert( calc.calculate("3 + 7") ); // 10 ``` -2. Then add the method `addMethod(name, func)` that teaches the calculator a new operation. It takes the operator `name` and the two-argument function `func(a,b)` that implements it. +2. Então, adicione o método `addMethod(name, func)` que ensina a calculadora uma nova operação. O método pega o operador `name` e a função que recebe dois argumentos `func(a,b)` para implementar a nova operação. - For instance, let's add the multiplication `*`, division `/` and power `**`: + Por exemplo, vamos adicionar multiplicação `*`, divisão `/` e potenciação `**`: ```js + let multCalc = new Calculator; + let divCalc = new Calculator; let powerCalc = new Calculator; - powerCalc.addMethod("*", (a, b) => a * b); - powerCalc.addMethod("/", (a, b) => a / b); + + multCalc.addMethod("*", (a, b) => a * b); + divCalc.addMethod("/", (a, b) => a / b); powerCalc.addMethod("**", (a, b) => a ** b); let result = powerCalc.calculate("2 ** 3"); alert( result ); // 8 ``` -- No brackets or complex expressions in this task. -- The numbers and the operator are delimited with exactly one space. -- There may be error handling if you'd like to add it. +- Sem colchetes ou expressões complexas neste exercício. +- Os números e o operador são separados por, exatamente, um espaço. +- Pode haver mensagem de erro se você desejar adicionar. diff --git a/1-js/05-data-types/05-array-methods/7-map-objects/solution.md b/1-js/05-data-types/05-array-methods/7-map-objects/solution.md index 5d8bf4a13..605f8de66 100644 --- a/1-js/05-data-types/05-array-methods/7-map-objects/solution.md +++ b/1-js/05-data-types/05-array-methods/7-map-objects/solution.md @@ -25,9 +25,9 @@ alert( usersMapped[0].id ); // 1 alert( usersMapped[0].fullName ); // John Smith ``` -Please note that in for the arrow functions we need to use additional brackets. +Por favor, note que para usar arrow functions, precisamos usar colchetes adicionais. -We can't write like this: +Não podemos escrevê-lo dessa forma: ```js let usersMapped = users.map(user => *!*{*/!* fullName: `${user.name} ${user.surname}`, @@ -35,9 +35,9 @@ let usersMapped = users.map(user => *!*{*/!* }); ``` -As we remember, there are two arrow functions: without body `value => expr` and with body `value => {...}`. +Como sabemos, existem dois tipos de arrow functions: sem corpo `value => expr` e com corpo `value => {...}`. -Here JavaScript would treat `{` as the start of function body, not the start of the object. The workaround is to wrap them in the "normal" brackets: +JavaScript irá tratar `{` como o começo do corpo de uma função, não o começo do objeto. A *gambiarra* é os colocar em volta de colchetes "normais", ou seja, primeiro os parênteses e depois os colchetes `({ ... })`: ```js let usersMapped = users.map(user => *!*({*/!* @@ -46,6 +46,6 @@ let usersMapped = users.map(user => *!*({*/!* })); ``` -Now fine. +Dessa forma, nosso código está correto. diff --git a/1-js/05-data-types/05-array-methods/7-map-objects/task.md b/1-js/05-data-types/05-array-methods/7-map-objects/task.md index b11d12155..d69026790 100644 --- a/1-js/05-data-types/05-array-methods/7-map-objects/task.md +++ b/1-js/05-data-types/05-array-methods/7-map-objects/task.md @@ -2,13 +2,13 @@ importance: 5 --- -# Map to objects +# Map para objetos -You have an array of `user` objects, each one has `name`, `surname` and `id`. +Você tem um array de objetos `user`, cada um possui `name`, `surname` e `id`. -Write the code to create another array from it, of objects with `id` and `fullName`, where `fullName` is generated from `name` and `surname`. +Escreva um código para criar um novo array a partir de `user`, também será um array de objetos com as propriedades `id` e `fullName`, onde `fullName` é gerado a partir da junção de `name` e `surname`. -For instance: +Exemplo: ```js no-beautify let john = { name: "John", surname: "Smith", id: 1 }; @@ -18,7 +18,7 @@ let mary = { name: "Mary", surname: "Key", id: 3 }; let users = [ john, pete, mary ]; *!* -let usersMapped = /* ... your code ... */ +let usersMapped = /* ... seu código ... */ */!* /* @@ -33,4 +33,4 @@ alert( usersMapped[0].id ) // 1 alert( usersMapped[0].fullName ) // John Smith ``` -So, actually you need to map one array of objects to another. Try using `=>` here. There's a small catch. \ No newline at end of file +Então, na realidade, você precisa copiar um array de objetos para o outro. Tente usar `=>` aqui. Há uma pegadinha neste exercício. \ No newline at end of file diff --git a/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md b/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md index 9f1ade707..0f3aeabdf 100644 --- a/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md +++ b/1-js/05-data-types/05-array-methods/8-sort-objects/solution.md @@ -11,7 +11,7 @@ let arr = [ pete, john, mary ]; sortByAge(arr); -// now sorted is: [john, mary, pete] +// agora a ordenação: [john, mary, pete] alert(arr[0].name); // John alert(arr[1].name); // Mary alert(arr[2].name); // Pete diff --git a/1-js/05-data-types/05-array-methods/8-sort-objects/task.md b/1-js/05-data-types/05-array-methods/8-sort-objects/task.md index 9a215c9f4..35559fffd 100644 --- a/1-js/05-data-types/05-array-methods/8-sort-objects/task.md +++ b/1-js/05-data-types/05-array-methods/8-sort-objects/task.md @@ -2,11 +2,11 @@ importance: 5 --- -# Sort users by age +# Ordene (sort) users por age -Write the function `sortByAge(users)` that gets an array of objects with the `age` property and sorts them by `age`. +Escreva a função `sortByAge(users)` que recebe um array de objetos com a propriedade `age` e o ordene por `age`. -For instance: +Por exemplo: ```js no-beautify let john = { name: "John", age: 25 }; @@ -17,7 +17,7 @@ let arr = [ pete, john, mary ]; sortByAge(arr); -// now: [john, mary, pete] +// agora: [john, mary, pete] alert(arr[0].name); // John alert(arr[1].name); // Mary alert(arr[2].name); // Pete diff --git a/1-js/05-data-types/05-array-methods/9-shuffle/solution.md b/1-js/05-data-types/05-array-methods/9-shuffle/solution.md index 31f7a2948..4a77c66aa 100644 --- a/1-js/05-data-types/05-array-methods/9-shuffle/solution.md +++ b/1-js/05-data-types/05-array-methods/9-shuffle/solution.md @@ -1,4 +1,4 @@ -The simple solution could be: +A solução simples pode ser: ```js run *!* @@ -12,18 +12,18 @@ shuffle(arr); alert(arr); ``` -That somewhat works, because `Math.random() - 0.5` is a random number that may be positive or negative, so the sorting function reorders elements randomly. +O código acima funciona porque `Math.random() - 0.5` é um número aleatório que pode ser positivo ou negativo, então a função de ordenação reordena os elementos aleatoriamente. -But because the sorting function is not meant to be used this way, not all permutations have the same probability. +Mas porque a função de ordenação não deve ser usada dessa maneira, nem todas as permutações têm a mesma probabilidade. -For instance, consider the code below. It runs `shuffle` 1000000 times and counts appearances of all possible results: +Por exemplo, considere o código abaixo. Ele executa `shuffle` 1000000 vezes e conta quantas foram as aparições de todos os resultados possíveis: ```js run function shuffle(array) { array.sort(() => Math.random() - 0.5); } -// counts of appearances for all possible permutations +// contagem de aparições de todos as permutações possíveis let count = { '123': 0, '132': 0, @@ -39,13 +39,13 @@ for (let i = 0; i < 1000000; i++) { count[array.join('')]++; } -// show counts of all possible permutations +// mostra a contagem de aparições de todos as permutações possíveis for (let key in count) { alert(`${key}: ${count[key]}`); } ``` -An example result (for V8, July 2017): +Um exemplo do resultado (for V8, July 2017): ```js 123: 250706 @@ -56,30 +56,30 @@ An example result (for V8, July 2017): 321: 125223 ``` -We can see the bias clearly: `123` and `213` appear much more often than others. +Podemos ver claramente: `123` e `213` aparece muito mais vezes do que os outros. -The result of the code may vary between JavaScript engines, but we can already see that the approach is unreliable. +O resultado do código pode variar entre as engines do JavaScript, mas já podemos ver que essa proposta não é confiável. -Why it doesn't work? Generally speaking, `sort` is a "black box": we throw an array and a comparison function into it and expect the array to be sorted. But due to the utter randomness of the comparison the black box goes mad, and how exactly it goes mad depends on the concrete implementation that differs between engines. +Por que não? Falando no geral, `sort` é uma "caixa preta": entregamos um array e uma função de comparação para ele e esperamos que o array seja ordenado. Porém, devido á aleatoriariedade total da comparação a caixa preta "enlouquece", e como exatamente ele "enlouquece" depende da implementação concreta que diferencia entre engines. -There are other good ways to do the task. For instance, there's a great algorithm called [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). The idea is to walk the array in the reverse order and swap each element with a random one before it: +Há outras formas melhores para fazer essa atividade. Por exemplo, existe um ótimo algoritmo chamado [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). A idéia é percorrer o array na ordem inversa e trocar cada elemento por um aleatório antes dele: ```js function shuffle(array) { for (let i = array.length - 1; i > 0; i--) { - let j = Math.floor(Math.random() * (i + 1)); // random index from 0 to i + let j = Math.floor(Math.random() * (i + 1)); // index aleatório de 0 á i - // swap elements array[i] and array[j] - // we use "destructuring assignment" syntax to achieve that - // you'll find more details about that syntax in later chapters - // same can be written as: + // troca os elementos do array[i] e do array[j] + // nós usamos a sintaxe "atribuição de desestruturação" para conseguir isso + // você vai encontrar mais detalhes sobre essa sintaxe em capítulos posteriores + // também pode ser escrito dessa forma: // let t = array[i]; array[i] = array[j]; array[j] = t [array[i], array[j]] = [array[j], array[i]]; } } ``` -Let's test it the same way: +Vamos testá-lo: ```js run function shuffle(array) { @@ -89,7 +89,7 @@ function shuffle(array) { } } -// counts of appearances for all possible permutations +// contagem de aparições de todos as permutações possíveis let count = { '123': 0, '132': 0, @@ -105,13 +105,13 @@ for (let i = 0; i < 1000000; i++) { count[array.join('')]++; } -// show counts of all possible permutations +// mostra a contagem de aparições de todos as permutações possíveis for (let key in count) { alert(`${key}: ${count[key]}`); } ``` -The example output: +O resultado do exemplo: ```js 123: 166693 @@ -122,6 +122,6 @@ The example output: 321: 166316 ``` -Looks good now: all permutations appear with the same probability. +Parece bom agora: todas as permutações aparecem com a mesma probabilidade. -Also, performance-wise the Fisher-Yates algorithm is much better, there's no "sorting" overhead. +Além disso, em termos de performance, o algoritmo Fisher-Yates é muito melhor, não há sobrecarga de ordenação. diff --git a/1-js/05-data-types/05-array-methods/9-shuffle/task.md b/1-js/05-data-types/05-array-methods/9-shuffle/task.md index 970c53417..baebef22e 100644 --- a/1-js/05-data-types/05-array-methods/9-shuffle/task.md +++ b/1-js/05-data-types/05-array-methods/9-shuffle/task.md @@ -2,11 +2,11 @@ importance: 3 --- -# Shuffle an array +# Embaralhe um array -Write the function `shuffle(array)` that shuffles (randomly reorders) elements of the array. +Escreva a função `shuffle(array)` que embaralha (reordena aleatoriamente) elementos do array. -Multiple runs of `shuffle` may lead to different orders of elements. For instance: +Múltiplas execuções de `shuffle` pode levar para diferentes ordenações dos elementos. Por exemplo: ```js let arr = [1, 2, 3]; @@ -22,4 +22,4 @@ shuffle(arr); // ... ``` -All element orders should have an equal probability. For instance, `[1,2,3]` can be reordered as `[1,2,3]` or `[1,3,2]` or `[3,1,2]` etc, with equal probability of each case. +Todas as ordenações dos elementos deve ter uma probabilidade igual. Por exemplo, `[1,2,3]` pode ser reordenado como `[1,2,3]` ou `[1,3,2]` ou `[3,1,2]` etc, com probabilidade iguais para cada caso. diff --git a/1-js/05-data-types/05-array-methods/article.md b/1-js/05-data-types/05-array-methods/article.md index a661b73b9..4d43da401 100644 --- a/1-js/05-data-types/05-array-methods/article.md +++ b/1-js/05-data-types/05-array-methods/article.md @@ -1,111 +1,111 @@ -# Array methods +# Métodos Arrays -Arrays provide a lot of methods. To make things easier, in this chapter they are split into groups. +Arrays nos fornece vários métodos. Para deixar esse assunto mais fácil de entender, neste capítulo esses métodos estão divididos em grupos. -## Add/remove items +## Adicionar/Remover itens -We already know methods that add and remove items from the beginning or the end: +Nós já conhecemos os métodos que adicionam e removem itens do início ou fim de um array: -- `arr.push(...items)` -- adds items to the end, -- `arr.pop()` -- extracts an item from the end, -- `arr.shift()` -- extracts an item from the beginning, -- `arr.unshift(...items)` -- adds items to the beginning. +- `arr.push(...itens)` -- adiciona itens no final de um array, +- `arr.pop()` -- retira um item do final de um array, +- `arr.shift()` -- retira um item do começo de um array, +- `arr.unshift(...itens)` -- adiciona itens no começo de um array. -Here are few others. +Abaixo apresentamos alguns outros métodos. ### splice -How to delete an element from the array? +Como deletar um elemento de um array? -The arrays are objects, so we can try to use `delete`: +Arrays são objetos, então podemos tentar usar `delete`: ```js run -let arr = ["I", "go", "home"]; +let arr = ["Eu", "vou", "casa"]; -delete arr[1]; // remove "go" +delete arr[1]; // remove "vou" -alert( arr[1] ); // undefined +alert( arr[1] ); // retornará undefined pois o elemento foi apagado -// now arr = ["I", , "home"]; +// atualizado arr = ["Eu", , "casa"]; alert( arr.length ); // 3 ``` -The element was removed, but the array still has 3 elements, we can see that `arr.length == 3`. +O elemento foi removido, mas o array ainda possui 3 elementos, nós podemos ver que `arr.length == 3`. -That's natural, because `delete obj.key` removes a value by the `key`. It's all it does. Fine for objects. But for arrays we usually want the rest of elements to shift and occupy the freed place. We expect to have a shorter array now. +Isso é normal porque `delete obj.chave` remove o valor pela `chave`. É um bom uso para objetos, mas para arrays, nós, normalmente, queremos que o resto dos elementos se movam e ocupem o espaço liberado. Esperávamos um array com menos elementos. -So, special methods should be used. +Dessa forma, métodos especiais devem ser usados. -The [arr.splice(str)](mdn:js/Array/splice) method is a swiss army knife for arrays. It can do everything: add, remove and insert elements. +O metodo [arr.splice(str)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) é um canivete suíço para arrays. Ele pode fazer qualquer coisa: adicionar, remover e inserir elementos. -The syntax is: +Sua sintaxe é: ```js -arr.splice(index[, deleteCount, elem1, ..., elemN]) +arr.splice(indexElementoArray[, quantidade, elem1, ..., elemN]) ``` -It starts from the position `index`: removes `deleteCount` elements and then inserts `elem1, ..., elemN` at their place. Returns the array of removed elements. +Começa em uma posição `indexElmentoArray`: remove uma certa `quantidade` de elementos e então insere `elem1, ..., elemN` em seus lugares. Ele retorna um array com os elementos removidos. -This method is easy to grasp by examples. +Esse metódo é melhor de se entender com exemplos. -Let's start with the deletion: +Vamos começar com a remoção de elementos: ```js run -let arr = ["I", "study", "JavaScript"]; +let arr = ["Eu", "estudo", "JavaScript"]; *!* -arr.splice(1, 1); // from index 1 remove 1 element +arr.splice(1, 1); // a partir da posição 1 remova 1 elemento */!* -alert( arr ); // ["I", "JavaScript"] +alert( arr ); // ["Eu", "JavaScript"] ``` -Easy, right? Starting from the index `1` it removed `1` element. +Fácil, não é? Começando pela posição `1` o método removeu `1` elemento. -In the next example we remove 3 elements and replace them with the other two: +No próximo exemplo vamos remover 3 elementos e substituí-los por outros dois elementos: ```js run -let arr = [*!*"I", "study", "JavaScript",*/!* "right", "now"]; +let arr = [*!*"Eu", "estudo", "JavaScript",*/!* "agora", "mesmo"]; -// remove 3 first elements and replace them with another -arr.splice(0, 3, "Let's", "dance"); +// remove os 3 primeiros elementos e os substitui por outros +arr.splice(0, 3, "Vamos", "dançar"); -alert( arr ) // now [*!*"Let's", "dance"*/!*, "right", "now"] +alert( arr ) // atualizado [*!*"Vamos", "dançar"*/!*, "agora", "mesmo"] ``` -Here we can see that `splice` returns the array of removed elements: +Abaixo podemos ver que `splice` retorna um array dos elementos removidos: ```js run -let arr = [*!*"I", "study",*/!* "JavaScript", "right", "now"]; +let arr = [*!*"Eu", "estudo",*/!* "JavaScript", "agora", "mesmo"]; -// remove 2 first elements -let removed = arr.splice(0, 2); +// remove os 2 primeiros elementos +let removido = arr.splice(0, 2); -alert( removed ); // "I", "study" <-- array of removed elements +alert( removido ); // "Eu", "estudo" <-- array de elementos removidos ``` -The `splice` method is also able to insert the elements without any removals. For that we need to set `deleteCount` to `0`: +O método `splice` também permite inserir elementos sem remover outros. Para isso, devemos colocar a `quantidade` em `0`: ```js run -let arr = ["I", "study", "JavaScript"]; +let arr = ["Eu", "estudo", "JavaScript"]; -// from index 2 -// delete 0 -// then insert "complex" and "language" -arr.splice(2, 0, "complex", "language"); +// a partir da posição 2 +// delete 0 elementos +// então insira "linguagem" e "complexa" +arr.splice(2, 0, "linguagem", "complexa"); -alert( arr ); // "I", "study", "complex", "language", "JavaScript" +alert( arr ); // "Eu", "estudo", "linguagem", "complexa", "JavaScript" ``` -````smart header="Negative indexes allowed" -Here and in other array methods, negative indexes are allowed. They specify the position from the end of the array, like here: +````smart header="Posição negativas são permitidas" +Neste e em outros métodos arrays, posições negativas são permitidas. Eles especificam a posição a partir do fim de um array, por exemplo: ```js run let arr = [1, 2, 5]; -// from index -1 (one step from the end) -// delete 0 elements, -// then insert 3 and 4 +// a partir da posição -1 (uma posição antes da última) +// delete 0 elementos, +// então insira 3 e 4 arr.splice(-1, 0, 3, 4); alert( arr ); // 1,2,3,4,5 @@ -114,19 +114,19 @@ alert( arr ); // 1,2,3,4,5 ### slice -The method [arr.slice](mdn:js/Array/slice) is much simpler than similar-looking `arr.splice`. +O método [arr.slice](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) é mais simples do que seu similar anterior `arr.splice`. -The syntax is: +Sua sintaxe é: ```js -arr.slice(start, end) +arr.slice(começo, fim) ``` -It returns a new array containing all items from index `"start"` to `"end"` (not including `"end"`). Both `start` and `end` can be negative, in that case position from array end is assumed. +Ele retorna um novo array contendo todos os itens a partir da posição `"começo"` até `"fim"` (ele não inclui o valor da posição `"fim"`). Ambos `começo` e `fim` podem ser negativos, nesse caso, a posição do final da array é assumida. -It works like `str.slice`, but makes subarrays instead of substrings. +Funciona como `str.slice`, porém este cria subarrays em vez de substrings. -For instance: +Por exemplo: ```js run let str = "test"; @@ -141,108 +141,109 @@ alert( arr.slice(-2) ); // s,t ### concat -The method [arr.concat](mdn:js/Array/concat) joins the array with other arrays and/or items. +O método [arr.concat](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) une um array com outros arrays e/ou itens. -The syntax is: +Sua sintaxe é: ```js arr.concat(arg1, arg2...) ``` -It accepts any number of arguments -- either arrays or values. +Este método aceita qualquer número de argumentos -- sendo arrays ou valores. -The result is a new array containing items from `arr`, then `arg1`, `arg2` etc. +O resultado vai ser um novo array contendo itens do `arr`, e também do `arg1`, `arg2` etc. -If an argument is an array or has `Symbol.isConcatSpreadable` property, then all its elements are copied. Otherwise, the argument itself is copied. +Se o argumento for um array ou possuir a propriedade `Symbol.isConcatSpreadable`, então todos seus elementos são copiados. Caso contrário, o argumento em si é copiado. -For instance: +Veja o exemplo: ```js run let arr = [1, 2]; -// merge arr with [3,4] +// une arr com [3,4] alert( arr.concat([3, 4])); // 1,2,3,4 -// merge arr with [3,4] and [5,6] +// une arr com [3,4] e [5,6] alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6 -// merge arr with [3,4], then add values 5 and 6 +// une arr com [3,4], e então adiciona os valores 5 e 6 alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6 ``` -Normally, it only copies elements from arrays ("spreads" them). Other objects, even if they look like arrays, added as a whole: +Normalmente, ele somente copia elementos de um array. Outros objetos, mesmo que eles se pareçam com arrays, são adicionados como um todo: ```js run let arr = [1, 2]; -let arrayLike = { - 0: "something", +let exemploDeArray = { + 0: "algo", length: 1 }; -alert( arr.concat(arrayLike) ); // 1,2,[object Object] -//[1, 2, arrayLike] +alert( arr.concat(exemploDeArray) ); // 1,2,[objeto Objeto] +//[1, 2, exemploDeArray] copiou a array em vez de seus elementos armazenados ``` -...But if an array-like object has `Symbol.isConcatSpreadable` property, then its elements are added instead: +...Mas se um array parecido com um objeto possui a propriedade `Symbol.isConcatSpreadable`, então os seus elementos são adicionados: ```js run let arr = [1, 2]; -let arrayLike = { - 0: "something", - 1: "else", +let exemploDeArray = { + 0: "qualquer", + 1: "coisa", *!* [Symbol.isConcatSpreadable]: true, */!* length: 2 }; -alert( arr.concat(arrayLike) ); // 1,2,something,else +alert( arr.concat(exemploDeArray) ); // 1,2,qualquer,coisa ``` ## Iterate: forEach -The [arr.forEach](mdn:js/Array/forEach) method allows to run a function for every element of the array. +O método [arr.forEach](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) permite executar uma função para cada elemento de um array. -The syntax: +Sua sintaxe: ```js arr.forEach(function(item, index, array) { - // ... do something with item + // ... faça algo com o item }); ``` +`index` sendo a posição do item. -For instance, this shows each element of the array: +Observe o exemplo abaixo, o código mostra cada elemento de um array: ```js run -// for each element call alert +// para cada elemento chame o alert ["Bilbo", "Gandalf", "Nazgul"].forEach(alert); ``` -And this code is more elaborate about their positions in the target array: +Este código é mais elaborado e mostra a posição de cada elemento: ```js run ["Bilbo", "Gandalf", "Nazgul"].forEach((item, index, array) => { - alert(`${item} is at index ${index} in ${array}`); + alert(`${item} está na posição ${index} em ${array}`); }); ``` -The result of the function (if it returns any) is thrown away and ignored. +O resultado da função (se retornar algum) é descartado e ignorado. -## Searching in array +## Buscando valores em um array -These are methods to search for something in an array. +Estes são métodos para procurar algo em um array. -### indexOf/lastIndexOf and includes +### indexOf/lastIndexOf e includes -The methods [arr.indexOf](mdn:js/Array/indexOf), [arr.lastIndexOf](mdn:js/Array/lastIndexOf) and [arr.includes](mdn:js/Array/includes) have the same syntax and do essentially the same as their string counterparts, but operate on items instead of characters: +Os métodos [arr.indexOf](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf), [arr.lastIndexOf](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf) e [arr.includes](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/contains) possuem a mesma sintaxe e fazem, essencialmente, a mesma coisa que acontece com as strings, entretanto, eles operam nos itens de um array em vez de caracteres como feito nas strings: -- `arr.indexOf(item, from)` looks for `item` starting from index `from`, and returns the index where it was found, otherwise `-1`. -- `arr.lastIndexOf(item, from)` -- same, but looks from right to left. -- `arr.includes(item, from)` -- looks for `item` starting from index `from`, returns `true` if found. +- `arr.indexOf(item, from)` -- procura por `item` começando pela posição `from`, e retorna o index/posição onde o elemento foi encontrado, caso o elemento não seja encontrado, o método retornará `-1`. +- `arr.lastIndexOf(item, from)` -- faz o mesmo que o método acima, porém faz uma busca começando da direita para esquerda. +- `arr.includes(item, from)` -- procura por `item` começando da posição `from`, retorna `true` se achado. -For instance: +Veja o exemplo: ```js run let arr = [1, 0, false]; @@ -254,110 +255,109 @@ alert( arr.indexOf(null) ); // -1 alert( arr.includes(1) ); // true ``` -Note that the methods use `===` comparison. So, if we look for `false`, it finds exactly `false` and not the zero. +Note que o método usa `===` para fazer a comparação. Então, se procuramos por `false`, o método achará exatamente `false` e não zero. -If we want to check for inclusion, and don't want to know the exact index, then `arr.includes` is preferred. +Se queremos saber se um elemento está incluso em um array porém sem necessariamente saber qual sua posição, então `arr.includes` é preferível. -Also, a very minor difference of `includes` is that it correctly handles `NaN`, unlike `indexOf/lastIndexOf`: +Além disso, uma pequena diferença que o `includes` possui é que ele aceita `NaN`, ao contrário de `indexOf/lastIndexOf`: ```js run const arr = [NaN]; -alert( arr.indexOf(NaN) ); // -1 (should be 0, but === equality doesn't work for NaN) -alert( arr.includes(NaN) );// true (correct) +alert( arr.indexOf(NaN) ); // -1 (deveria ser 0, mas === igualdade não funciona com NaN) +alert( arr.includes(NaN) );// true (correto) ``` -### find and findIndex +### find e findIndex -Imagine we have an array of objects. How do we find an object with the specific condition? +Imagine que tenhamos um array de objetos. Como achamos um objeto usando uma condição específica? -Here the [arr.find](mdn:js/Array/find) method comes in handy. +É nesses momentos que o método [arr.find](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/find) vem a calhar. -The syntax is: +Sua sintaxe é: ```js let result = arr.find(function(item, index, array) { - // if true is returned, item is returned and iteration is stopped - // for falsy scenario returns undefined + // se a condição de find resultar em true, então item é retornado e o laço é parado + // se resultar em falso é retornado o valor undefined }); ``` -The function is called repetitively for each element of the array: +A função dentro de `find` é chamada repetitivamente para cada elemento do array: -- `item` is the element. -- `index` is its index. -- `array` is the array itself. +- `item` é o elemento. +- `index` é sua posição. +- `array` é o array onde se encontra o elemento. -If it returns `true`, the search is stopped, the `item` is returned. If nothing found, `undefined` is returned. +Se a função resultar em `true`, a busca é parada e o `item` é retornado. Se nada for achado, `undefined` é retornado. -For example, we have an array of users, each with the fields `id` and `name`. Let's find the one with `id == 1`: +Por exemplo, nós temos um array de usuários, cada um com os campos `id` e `nome`. Vamos achar o usuário com `id == 1`: ```js run -let users = [ - {id: 1, name: "John"}, - {id: 2, name: "Pete"}, - {id: 3, name: "Mary"} +let usuarios = [ + {id: 1, nome: "John"}, + {id: 2, nome: "Pete"}, + {id: 3, nome: "Mary"} ]; -let user = users.find(item => item.id == 1); +let user = usuarios.find(item => item.id == 1); -alert(user.name); // John +alert(user.nome); // John ``` -In real life arrays of objects is a common thing, so the `find` method is very useful. +Na vida real, arrays de objetos é uma coisa comum, dessa forma, o método `find` é muito útil. -Note that in the example we provide to `find` the function `item => item.id == 1` with one argument. Other arguments of this function are rarely used. +Note que no exemplo nós demos para `find` uma função `item => item.id == 1` com somente um argumento. Os outros argumentos dessa função raramente são usados. -The [arr.findIndex](mdn:js/Array/findIndex) method is essentially the same, but it returns the index where the element was found instead of the element itself and `-1` is returned when nothing is found. +O método [arr.findIndex](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) é exatamente o mesmo, mas retorna a posição onde o elemento foi encontrado e não seu elemento e `-1` é retornado quando nada é encontrado. ### filter -The `find` method looks for a single (first) element that makes the function return `true`. +O método `find` procura por um único (e o primeiro) elemento que fizer a função retornar `true`. -If there may be many, we can use [arr.filter(fn)](mdn:js/Array/filter). +Se quisermos que retorne mais de um elemento, podemos usar [arr.filter(fn)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/filtro). -The syntax is similar to `find`, but filter continues to iterate for all array elements even if `true` is already returned: +A sintaxe é parecida com `find`, porém o `filter` continua o loop por todos os elementos do array mesmo se `true` já tiver sindo retornado: ```js -let results = arr.filter(function(item, index, array) { - // if true item is pushed to results and iteration continues - // returns empty array for complete falsy scenario +let resultado = arr.filter(function(item, index, array) { + //se um elemento que atende aos requisitos for alocado na variável resultado e o loop continuar + //retorna um array vazio por completar um cenário falso }); ``` -For instance: +Por exemplo: ```js run -let users = [ - {id: 1, name: "John"}, - {id: 2, name: "Pete"}, - {id: 3, name: "Mary"} +let usuarios = [ + {id: 1, nome: "John"}, + {id: 2, nome: "Pete"}, + {id: 3, nome: "Mary"} ]; -// returns array of the first two users -let someUsers = users.filter(item => item.id < 3); +//retorna um array com os dois primeiros usuários +let algunsUsuarios = usuarios.filter(item => item.id < 3); -alert(someUsers.length); // 2 +alert(algunsUsuarios.length); // 2 ``` -## Transform an array - -This section is about the methods transforming or reordering the array. +## Transformando um array +Esta seção irá abordar os métodos que transformam ou reorganizam um array. ### map -The [arr.map](mdn:js/Array/map) method is one of the most useful and often used. +O método [arr.map](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/map) é um dos mais úteis e usados por programadores. -The syntax is: +Sua sintaxe é: ```js -let result = arr.map(function(item, index, array) { - // returns the new value instead of item +let resultado = arr.map(function(item, index, array) { + //retorna um novo valor e não seu item }) ``` -It calls the function for each element of the array and returns the array of results. +Ele chama a função para cada elemento do array e retorna um array com o resultado. -For instance, here we transform each element into its length: +Abaixo, transformamos cada elemento em seu tamanho: ```js run let lengths = ["Bilbo", "Gandalf", "Nazgul"].map(item => item.length); @@ -366,30 +366,30 @@ alert(lengths); // 5,7,6 ### sort(fn) -The method [arr.sort](mdn:js/Array/sort) sorts the array *in place*. +O método [arr.sort](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) ordena um array colocando os elementos *em seus devidos lugares*. -For instance: +Exemplo: ```js run let arr = [ 1, 2, 15 ]; -// the method reorders the content of arr (and returns it) +//o método reordena o conteúdo do array (e o retorna) arr.sort(); alert( arr ); // *!*1, 15, 2*/!* ``` -Did you notice anything strange in the outcome? +Você notou alguma coisa estranha non resultado? -The order became `1, 15, 2`. Incorrect. But why? +A ordem ficou `1, 15, 2`. Incorreto. Mas por quê? -**The items are sorted as strings by default.** +**Os itens são ordenados como strings por padrão.** -Literally, all elements are converted to strings and then compared. So, the lexicographic ordering is applied and indeed `"2" > "15"`. +Literalmente, todos os elementos são convertidos para strings e então comparados. A ordenação lexicográfica é aplicada e, de fato, `"2" > "15"`. -To use our own sorting order, we need to supply a function of two arguments as the argument of `arr.sort()`. +Para usar nossa própria ordenação, precisamos produzir uma função que recebe dois argumentos como argumento de `arr.sort()`. -The function should work like this: +A função deve funcionar desse jeito: ```js function compare(a, b) { if (a > b) return 1; @@ -398,7 +398,7 @@ function compare(a, b) { } ``` -For instance: +Por exemplo: ```js run function compareNumeric(a, b) { @@ -416,13 +416,13 @@ arr.sort(compareNumeric); alert(arr); // *!*1, 2, 15*/!* ``` -Now it works as intended. +Agora funciona como pretendido. -Let's step aside and think what's happening. The `arr` can be array of anything, right? It may contain numbers or strings or html elements or whatever. We have a set of *something*. To sort it, we need an *ordering function* that knows how to compare its elements. The default is a string order. +Vamos parar um pouco e pensar sobre o que exatamente está acontecendo. O `arr` pode ser um array de qualquer coisa, correto? Ele pode conter números ou strings ou elementos HTML ou qualquer outra coisa. Nós vamos ter um array de *alguma coisa*. Para ordená-lo, precisamos de uma *função de ordenação* que saiba comparar os elementos. O padrão é uma ordenação de strings. -The `arr.sort(fn)` method has a built-in implementation of sorting algorithm. We don't need to care how it exactly works (an optimized [quicksort](https://en.wikipedia.org/wiki/Quicksort) most of the time). It will walk the array, compare its elements using the provided function and reorder them, all we need is to provide the `fn` which does the comparison. +O método `arr.sort(fn)` possui uma implementação interna (built-in) de ordenação de algoritmos. Não precisamos saber exatamente como funciona (na maioria do tempo, ele é [quicksort](https://pt.wikipedia.org/wiki/Quicksort) otimizado). Ele vai percorrer o array, comparar seus elementos usando a função providenciada e reordená-los, tudo que precisamos é fornecer o `fn` que irá fazer a comparação. -By the way, if we ever want to know which elements are compared -- nothing prevents from alerting them: +A propósito, se em algum momento quisermos saber quais elementos são comparados -- nada nos previne de usar um `alert` neles: ```js run [1, -2, 15, 2, 0, 8].sort(function(a, b) { @@ -430,13 +430,13 @@ By the way, if we ever want to know which elements are compared -- nothing preve }); ``` -The algorithm may compare an element multiple times in the process, but it tries to make as few comparisons as possible. +O algoritmo pode até comparar um elemento múltiplas vezes durante o processo, porém ele tenta fazer o menor número de comparações possíveis. -````smart header="A comparison function may return any number" -Actually, a comparison function is only required to return a positive number to say "greater" and a negative number to say "less". +````smart header="Uma função de comparação pode retornar qualquer número" +Na verdade, numa função de comparação é somente exigido que retorne um número positivo para dizer "maior que" e um negativo para "menor que". -That allows to write shorter functions: +Isso permite escrever funções menores: ```js run let arr = [ 1, 2, 15 ]; @@ -447,21 +447,21 @@ alert(arr); // *!*1, 2, 15*/!* ``` ```` -````smart header="Arrow functions for the best" -Remember [arrow functions](info:function-expressions-arrows#arrow-functions)? We can use them here for neater sorting: +````smart header="Arrow functions para o melhor" +Você se lembra de [arrow functions](info:function-expressions-arrows#arrow-functions)? Podemos usá-lo aqui para deixar o código mais limpo: ```js arr.sort( (a, b) => a - b ); ``` -This works exactly the same as the other, longer, version above. +Funciona exatamente como a outra versão acima. ```` ### reverse -The method [arr.reverse](mdn:js/Array/reverse) reverses the order of elements in `arr`. +O método [arr.reverse](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse) reverte a ordem dos elementos em `arr`. -For instance: +Exemplo: ```js run let arr = [1, 2, 3, 4, 5]; @@ -471,26 +471,27 @@ alert( arr ); // 5,4,3,2,1 ``` It also returns the array `arr` after the reversal. +Ele também retornar o array `arr` depois de revertê-lo. -### split and join +### split e join -Here's the situation from the real life. We are writing a messaging app, and the person enters the comma-delimited list of receivers: `John, Pete, Mary`. But for us an array of names would be much more comfortable than a single string. How to get it? +Aqui vai uma situação que ocorre na vida real. Digamos que estamos escrevendo uma aplicativo de mensagem e uma pessoa coloca uma lista dos recebedores delimitado por virgulas: `John, Pete, Mary`. Mas para nós um array de nomes seria muito mais confortável do que uma única string. Como fazer isso? -The [str.split(delim)](mdn:js/String/split) method does exactly that. It splits the string into an array by the given delimiter `delim`. +O método [str.split(delim)](https://www.devmedia.com.br/javascript-split-dividindo-separando-strings/39254) faz exatamente isso. Ele separa a string em uma array dado por seu delimitador `delim`. -In the example below, we split by a comma followed by space: +No exemplo abaixo, nós separamos por uma vírgula seguido por um espaço: ```js run -let names = 'Bilbo, Gandalf, Nazgul'; +let nomes = 'Bilbo, Gandalf, Nazgul'; -let arr = names.split(', '); +let arr = nomes.split(', '); -for (let name of arr) { - alert( `A message to ${name}.` ); // A message to Bilbo (and other names) +for (let nome of arr) { + alert( `Uma mensagem para ${name}.` ); // Uma mensagem para Bilbo (outros nomes) } ``` -The `split` method has an optional second numeric argument -- a limit on the array length. If it is provided, then the extra elements are ignored. In practice it is rarely used though: +O método `split` possui um segundo argumento numérico opcional -- um limite para o tamanho de uma array. Se for aprovado, então os outros elemento são ignorados. Na prática, é raramente usado: ```js run let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2); @@ -498,19 +499,19 @@ let arr = 'Bilbo, Gandalf, Nazgul, Saruman'.split(', ', 2); alert(arr); // Bilbo, Gandalf ``` -````smart header="Split into letters" -The call to `split(s)` with an empty `s` would split the string into an array of letters: +````smart header="Separe por letras" +Ao chamar `split(s)` com o `s` vazio, separaria a string e teríamos um array de letras: ```js run -let str = "test"; +let str = "teste"; -alert( str.split('') ); // t,e,s,t +alert( str.split('') ); // t,e,s,t,e ``` ```` -The call [arr.join(separator)](mdn:js/Array/join) does the reverse to `split`. It creates a string of `arr` items glued by `separator` between them. +O método [arr.join(separator)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/join) faz o contrário de `split`. Ele cria uma string dos itens de `arr` juntando-os por um `separator` entre eles. -For instance: +Por exemplo: ```js run let arr = ['Bilbo', 'Gandalf', 'Nazgul']; @@ -522,13 +523,13 @@ alert( str ); // Bilbo;Gandalf;Nazgul ### reduce/reduceRight -When we need to iterate over an array -- we can use `forEach`, `for` or `for..of`. +Quando precisamos percorrer um array -- podemos usar `forEach`, `for` ou `for..of`. -When we need to iterate and return the data for each element -- we can use `map`. +Quando precisamos percorrer e retornar uma informação por cada elemento -- usamos o `map`. -The methods [arr.reduce](mdn:js/Array/reduce) and [arr.reduceRight](mdn:js/Array/reduceRight) also belong to that breed, but are a little bit more intricate. They are used to calculate a single value based on the array. +Os métodos [arr.reduce](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) e [arr.reduceRight](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight) também pertence á esse grupo, porém eles podem ser um pouco mais confusos. Eles são usados para calcular um único valor baseado em um array. -The syntax is: +Sua sintaxe é: ```js let value = arr.reduce(function(previousValue, item, index, array) { @@ -536,98 +537,106 @@ let value = arr.reduce(function(previousValue, item, index, array) { }, initial); ``` -The function is applied to the elements. You may notice the familiar arguments, starting from the 2nd: +A função é aplicada nos elementos. Você pode ter notado os argumentos familiares, começando pelo o segundo: -- `item` -- is the current array item. -- `index` -- is its position. -- `array` -- is the array. +- `item` -- é o atual item da array. +- `index` -- é sua posição. +- `array` -- é a array. -So far, like `forEach/map`. But there's one more argument: +Até agora, é similiar ao método `forEach/map`. Porém há mais um argumento: -- `previousValue` -- is the result of the previous function call, `initial` for the first call. +- `previousValue` -- é o resultado da última chamada da função, `initial` seria o valor inicial. -The easiest way to grasp that is by example. +O jeito mais fácil de se entender é por meio de exemplos. -Here we get a sum of array in one line: +Aqui vamos somar os elementos de um array: ```js run let arr = [1, 2, 3, 4, 5]; -let result = arr.reduce((sum, current) => sum + current, 0); +let resultado = arr.reduce((sum, current) => { + + return sum + current, + +}, 0); -alert(result); // 15 +alert(resultado); // 15 ``` -Here we used the most common variant of `reduce` which uses only 2 arguments. +Neste exemplo, usamos a forma mais simples de se usar `reduce`, o qual recebe somente 2 argumentos. -Let's see the details of what's going on. +Vamos entender os detalhes do que está acontecendo. -1. On the first run, `sum` is the initial value (the last argument of `reduce`), equals `0`, and `current` is the first array element, equals `1`. So the result is `1`. -2. On the second run, `sum = 1`, we add the second array element (`2`) to it and return. -3. On the 3rd run, `sum = 3` and we add one more element to it, and so on... +1. Na 1º execução, podemos notar que o último argumento de `reduce` é igual a `0`, logo esse será o valor inicial de `sum`, e `current` terá o valor do primeiro elemento do array: `1`. A função está retornando a soma das variáveis `sum` e `current`, então o resultado é `1`. +2. Na 2º execução, `sum` passa a ter o resultado como valor `sum = 1` e `current` passa a ter o segundo elemento do array `current = 2` e, então, retorna a soma destes. +3. Na 3º execução, `sum = 3` e `current` passa a ter o próximo elemento do array e assim por diante... -The calculation flow: +Abaixo, a imagem mostra o fluxo da calculação: ![](reduce.svg) -Or in the form of a table, where each row represents a function call on the next array element: +Ou por meio de uma tabela, onde cada linha representa uma chamada da função no próximo elemento do array: -| |`sum`|`current`|`result`| +| |`sum`|`current`|`resultado`| |---|-----|---------|---------| -|the first call|`0`|`1`|`1`| -|the second call|`1`|`2`|`3`| -|the third call|`3`|`3`|`6`| -|the fourth call|`6`|`4`|`10`| -|the fifth call|`10`|`5`|`15`| +|1º chamada|`0`|`1`|`1`| +|2º chamada|`1`|`2`|`3`| +|3º chamada|`3`|`3`|`6`| +|4º chamada|`6`|`4`|`10`| +|5º chamada|`10`|`5`|`15`| -As we can see, the result of the previous call becomes the first argument of the next one. +Como podemos ver, o resultado da última chamada se torna o valor do primeiro argumento na próxima chamada. -We also can omit the initial value: +Podemos também omitir o valor inicial: ```js run let arr = [1, 2, 3, 4, 5]; -// removed initial value from reduce (no 0) -let result = arr.reduce((sum, current) => sum + current); +// valor inicial de reduce foi removido (sem 0) +let resultado = arr.reduce((sum, current) => { + + return sum + current + +}); -alert( result ); // 15 +alert( resultado ); // 15 ``` -The result is the same. That's because if there's no initial, then `reduce` takes the first element of the array as the initial value and starts the iteration from the 2nd element. +O resultado é o mesmo. Isto ocorre porque, se não houver um valor inicial, `reduce` irá pegar o primeiro elemento do array como este valor e `current` começará a partir do 2º elemento. -The calculation table is the same as above, minus the first row. +A tabela de calculação será a mesma de cima, menos a primeira linha. -But such use requires an extreme care. If the array is empty, then `reduce` call without initial value gives an error. +Porém, o uso deste método requer extremo cuidado. Se um array estiver vazio e `reduce` for acionado sem um valor inicial, será retornado um erro. -Here's an example: +Aqui esta um exemplo: ```js run let arr = []; -// Error: Reduce of empty array with no initial value -// if the initial value existed, reduce would return it for the empty arr. +// Erro: Reduce de array vazia sem valor inicial +// se o valor inicial existir, reduce irá retorná-lo para dentro da array vazia. arr.reduce((sum, current) => sum + current); ``` -So it's advised to always specify the initial value. +Portanto, é aconselhável que o valor inicial seja sempre colocado. -The method [arr.reduceRight](mdn:js/Array/reduceRight) does the same, but goes from right to left. +O método [arr.reduceRight](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight) faz o mesmo, mas começando da direita para a esquerda. ## Array.isArray -Arrays do not form a separate language type. They are based on objects. +Arrays não formam um outro tipo de linguagem. Eles são baseados em objetos. -So `typeof` does not help to distinguish a plain object from an array: +Mesmo usando `typeof` não é possível distinguir um objeto de um array: ```js run -alert(typeof {}); // object -alert(typeof []); // same +alert(typeof {}); // objeto +alert(typeof []); // objeto ``` -...But arrays are used so often that there's a special method for that: [Array.isArray(value)](mdn:js/Array/isArray). It returns `true` if the `value` is an array, and `false` otherwise. +...Mas arrays são usados tão frequentemente que há um método especial para isso: [Array.isArray(valor)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). Este método retorna `true` se o `valor` for um array e `false` se não for. ```js run alert(Array.isArray({})); // false @@ -635,98 +644,98 @@ alert(Array.isArray({})); // false alert(Array.isArray([])); // true ``` -## Most methods support "thisArg" +## A maioria dos métodos suportam "thisArg" -Almost all array methods that call functions -- like `find`, `filter`, `map`, with a notable exception of `sort`, accept an optional additional parameter `thisArg`. +Quase todos os métodos arrays que chamam uma função -- como `find`, `filter`, `map`, com exceção de `sort` -- aceitam um parâmetro adicional opcional `thisArg`. -That parameter is not explained in the sections above, because it's rarely used. But for completeness we have to cover it. +Este parâmetro não foi explicado nas seções anteriores porque é raramente usado. Entretanto, para um ensinamento melhor e completo, decidimos mostrá-lo. -Here's the full syntax of these methods: +Abaixo mostramos a sintaxe completa destes métodos: ```js arr.find(func, thisArg); arr.filter(func, thisArg); arr.map(func, thisArg); // ... -// thisArg is the optional last argument +// thisArg é o último argumento opcional ``` -The value of `thisArg` parameter becomes `this` for `func`. +O valor do parâmetro `thisArg` se torna o `this` para `func`. -For instance, here we use an object method as a filter and `thisArg` comes in handy: +No exemplo abaixo, usamos um objeto como filtro e acabou que `thisArg` facilitou o uso do método: ```js run -let user = { - age: 18, - younger(otherUser) { - return otherUser.age < this.age; +let usuario = { + idade: 18, + maisNovo(outroUsuario) { + return outroUsuario.idade < this.idade; } }; -let users = [ - {age: 12}, - {age: 16}, - {age: 32} +let usuarios = [ + {idade: 12}, + {idade: 16}, + {idade: 32} ]; *!* -// find all users younger than user -let youngerUsers = users.filter(user.younger, user); +// ache todos os usuarios mais novos que o usuario +let maisNovoUsers = usuarios.filter(usuario.maisNovo, usuario); */!* -alert(youngerUsers.length); // 2 +alert(maisNovoUsuario.length); // 2 ``` -In the call above, we use `user.younger` as a filter and also provide `user` as the context for it. If we didn't provide the context, `users.filter(user.younger)` would call `user.younger` as a standalone function, with `this=undefined`. That would mean an instant error. +No exemplo acima, nós usamos `usuario.maisNovo` como um filtro e também fornecemos `usuario` como contexto. Se não tivéssemos fornecido o contexto, `usuarios.filter(usuario.maisNovo)` iria chamar `usuario.maisNovo` como uma funçao de parâmetro único, com `this=undefined`. No final, ele retornaria um erro. -## Summary +## Resumo -A cheatsheet of array methods: +Uma *cola* com os métodos arrays abordados: -- To add/remove elements: - - `push(...items)` -- adds items to the end, - - `pop()` -- extracts an item from the end, - - `shift()` -- extracts an item from the beginning, - - `unshift(...items)` -- adds items to the beginning. - - `splice(pos, deleteCount, ...items)` -- at index `pos` delete `deleteCount` elements and insert `items`. - - `slice(start, end)` -- creates a new array, copies elements from position `start` till `end` (not inclusive) into it. - - `concat(...items)` -- returns a new array: copies all members of the current one and adds `items` to it. If any of `items` is an array, then its elements are taken. +- Para adicionar/remover elementos: + - `push(...items)` -- adiciona itens no final, + - `pop()` -- retira um item do final, + - `shift()` -- retira um item do começo, + - `unshift(...items)` -- adiciona um item no começo. + - `splice(posicao, quantidade, ...items)` -- no index `posicao`, deleta uma certa `quantidade` de elementos e insere outros `items`. + - `slice(comeco, fim)` -- cria um novo array, copia elementos a partir da posição `comeco` até `fim` (que não é incluso) para dentro do array. + - `concat(...items)` -- retorna um novo array: une elementos de um array atual com outros `items` e adiciona a array nova. Se algum `items` for um array, então seus elementos também são capturados e adicionados. -- To search among elements: - - `indexOf/lastIndexOf(item, pos)` -- look for `item` starting from position `pos`, return the index or `-1` if not found. - - `includes(value)` -- returns `true` if the array has `value`, otherwise `false`. - - `find/filter(func)` -- filter elements through the function, return first/all values that make it return `true`. - - `findIndex` is like `find`, but returns the index instead of a value. +- Para procurar entre os elementos: + - `indexOf/lastIndexOf(item, posicao)` -- procura por `item` começando pela `posicao`, retorna o index/posição ou `-1` se não for encontrado. + - `includes(valor)` -- retorna `true` se o array possuir o `valor`, do contrário, retornará `false`. + - `find/filter(func)` -- filtra elementos por meio de uma função, retorna o primeiro - ou todos - valor que fizer a função retornar `true`. + - `findIndex` é como `find`, mas retorna o index e não o valor. -- To iterate over elements: - - `forEach(func)` -- calls `func` for every element, does not return anything. +- Para percorrer os elementos: + - `forEach(func)` -- chama `func` para cada elemento, não retorna um valor. -- To transform the array: - - `map(func)` -- creates a new array from results of calling `func` for every element. - - `sort(func)` -- sorts the array in-place, then returns it. - - `reverse()` -- reverses the array in-place, then returns it. - - `split/join` -- convert a string to array and back. - - `reduce(func, initial)` -- calculate a single value over the array by calling `func` for each element and passing an intermediate result between the calls. +- Para transformar um array: + - `map(func)` -- cria um novo array a partir do resultado da chamada de `func` para cada elemento. + - `sort(func)` -- ordena o array e o retorna. + - `reverse()` -- inverte o array e o retorna. + - `split/join` -- converte uma string para array/array para string. + - `reduce(func, initial)` -- calcula um único valor a partir de um array ao chamar `func` para cada elemento e passando um resultado intermediário entre as chamadas. -- Additionally: - - `Array.isArray(arr)` checks `arr` for being an array. +- Adicional: + - `Array.isArray(arr)` checa se `arr` é um array. -Please note that methods `sort`, `reverse` and `splice` modify the array itself. +Por favor, note que os métodos `sort`, `reverse` e `splice` modificam o array. -These methods are the most used ones, they cover 99% of use cases. But there are few others: +Este métodos são os mais usados, eles cobrem 99% em casos de uso. Porém, existem outros: -- [arr.some(fn)](mdn:js/Array/some)/[arr.every(fn)](mdn:js/Array/every) checks the array. +- [arr.some(fn)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/some)/[arr.every(fn)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/every) examina o array. - The function `fn` is called on each element of the array similar to `map`. If any/all results are `true`, returns `true`, otherwise `false`. + A função `fn` é chamada em cada elemento do array como em `map`. Se algum/todos os resultados for `true`, retorna `true`, do contrário `false`. -- [arr.fill(value, start, end)](mdn:js/Array/fill) -- fills the array with repeating `value` from index `start` to `end`. +- [arr.fill(valor, comeco, fim)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/fill) -- preenche um array com o `valor` dado repetitivamente a partir da posição `comeco` até `fim`. -- [arr.copyWithin(target, start, end)](mdn:js/Array/copyWithin) -- copies its elements from position `start` till position `end` into *itself*, at position `target` (overwrites existing). +- [arr.copyWithin(target, start, end)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/copyWithin) -- copia *seus próprios elementos* e os leva para outra posição *dentro da mesma array*. A cópia dos elementos começa a partir da posição `start` até a posição `end`, e os elementos são realocados para a posição `target` (sobescrevendo os elementos existentes). Este método não adiciona novos itens ao array. -For the full list, see the [manual](mdn:js/Array). +Para a lista completa, veja o [manual](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array). -From the first sight it may seem that there are so many methods, quite difficult to remember. But actually that's much easier than it seems. +Á primeira vista, pode parecer que são muitos métodos e que se torna difícil de lembrá-los. Mas, na verdade, isso é mais simples do que parece. -Look through the cheatsheet just to be aware of them. Then solve the tasks of this chapter to practice, so that you have experience with array methods. +Examine esta lista de *cola* só para ter uma noção deles e depois resolva os exercícios deste capítulo para praticar. Desta forma, você vai ter uma experiência com métodos arrays. -Afterwards whenever you need to do something with an array, and you don't know how -- come here, look at the cheatsheet and find the right method. Examples will help you to write it correctly. Soon you'll automatically remember the methods, without specific efforts from your side. +Mais tarde, sempre que precisar fazer algo com arrays -- e você não souber como -- venha até aqui, olhe nossa cola e ache o método correto. Exemplos vão lhe ajudar a escrever corretamente. Logo você irá lembrar dos métodos automaticamente, sem esforços específicos.