From 9e4ac410aeeaa6b8fb2b1e426c40be6493d9d18e Mon Sep 17 00:00:00 2001 From: Diogo Marciano Date: Sun, 8 Nov 2026 19:52:08 -0300 Subject: [PATCH 1/2] Translate "Arrays" article to Portuguese Co-Authored-By: Claude Sonnet 5 --- .../04-array/1-item-value/solution.md | 4 +- .../04-array/1-item-value/task.md | 8 +- .../10-maximal-subarray/_js.view/test.js | 18 +- .../04-array/10-maximal-subarray/solution.md | 44 +-- .../04-array/10-maximal-subarray/task.md | 18 +- .../04-array/2-create-array/task.md | 16 +- .../04-array/3-call-array-this/solution.md | 6 +- .../04-array/3-call-array-this/task.md | 4 +- .../04-array/5-array-input-sum/solution.md | 6 +- .../04-array/5-array-input-sum/task.md | 12 +- 1-js/05-data-types/04-array/array-pop.svg | 2 +- 1-js/05-data-types/04-array/array-shift.svg | 2 +- 1-js/05-data-types/04-array/article.md | 350 +++++++++--------- images.yml | 17 + 14 files changed, 262 insertions(+), 245 deletions(-) diff --git a/1-js/05-data-types/04-array/1-item-value/solution.md b/1-js/05-data-types/04-array/1-item-value/solution.md index e631f1c70..38725a5d1 100644 --- a/1-js/05-data-types/04-array/1-item-value/solution.md +++ b/1-js/05-data-types/04-array/1-item-value/solution.md @@ -1,4 +1,4 @@ -The result is `4`: +O resultado é `4`: ```js run @@ -13,5 +13,5 @@ alert( fruits.length ); // 4 */!* ``` -That's because arrays are objects. So both `shoppingCart` and `fruits` are the references to the same array. +Isso acontece porque arrays são objetos. Então tanto `shoppingCart` quanto `fruits` são referências para o mesmo array. diff --git a/1-js/05-data-types/04-array/1-item-value/task.md b/1-js/05-data-types/04-array/1-item-value/task.md index 4fcf384fb..c4be70235 100644 --- a/1-js/05-data-types/04-array/1-item-value/task.md +++ b/1-js/05-data-types/04-array/1-item-value/task.md @@ -2,18 +2,18 @@ importance: 3 --- -# Is array copied? +# O array é copiado? -What is this code going to show? +O que esse código vai mostrar? ```js let fruits = ["Apples", "Pear", "Orange"]; -// push a new value into the "copy" +// insere um novo valor na "cópia" let shoppingCart = fruits; shoppingCart.push("Banana"); -// what's in fruits? +// o que tem em fruits? alert( fruits.length ); // ? ``` diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/_js.view/test.js b/1-js/05-data-types/04-array/10-maximal-subarray/_js.view/test.js index b44e76fe7..f41e14691 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/_js.view/test.js +++ b/1-js/05-data-types/04-array/10-maximal-subarray/_js.view/test.js @@ -1,37 +1,37 @@ describe("getMaxSubSum", function() { - it("maximal subsum of [1, 2, 3] equals 6", function() { + it("subsoma máxima de [1, 2, 3] é igual a 6", function() { assert.equal(getMaxSubSum([1, 2, 3]), 6); }); - it("maximal subsum of [-1, 2, 3, -9] equals 5", function() { + it("subsoma máxima de [-1, 2, 3, -9] é igual a 5", function() { assert.equal(getMaxSubSum([-1, 2, 3, -9]), 5); }); - it("maximal subsum of [-1, 2, 3, -9, 11] equals 11", function() { + it("subsoma máxima de [-1, 2, 3, -9, 11] é igual a 11", function() { assert.equal(getMaxSubSum([-1, 2, 3, -9, 11]), 11); }); - it("maximal subsum of [-2, -1, 1, 2] equals 3", function() { + it("subsoma máxima de [-2, -1, 1, 2] é igual a 3", function() { assert.equal(getMaxSubSum([-2, -1, 1, 2]), 3); }); - it("maximal subsum of [100, -9, 2, -3, 5] equals 100", function() { + it("subsoma máxima de [100, -9, 2, -3, 5] é igual a 100", function() { assert.equal(getMaxSubSum([100, -9, 2, -3, 5]), 100); }); - it("maximal subsum of [] equals 0", function() { + it("subsoma máxima de [] é igual a 0", function() { assert.equal(getMaxSubSum([]), 0); }); - it("maximal subsum of [-1] equals 0", function() { + it("subsoma máxima de [-1] é igual a 0", function() { assert.equal(getMaxSubSum([-1]), 0); }); - it("maximal subsum of [-1, -2] equals 0", function() { + it("subsoma máxima de [-1, -2] é igual a 0", function() { assert.equal(getMaxSubSum([-1, -2]), 0); }); - it("maximal subsum of [2, -8, 5, -1, 2, -3, 2] equals 6", function() { + it("subsoma máxima de [2, -8, 5, -1, 2, -3, 2] é igual a 6", function() { assert.equal(getMaxSubSum([2, -8, 5, -1, 2, -3, 2]), 6); }); }); diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index 7e1ca3bde..6c007a068 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -1,43 +1,43 @@ -# Slow solution +# Solução lenta -We can calculate all possible subsums. +Podemos calcular todas as somas parciais possíveis. -The simplest way is to take every element and calculate sums of all subarrays starting from it. +A forma mais simples é pegar cada elemento e calcular as somas de todos os subarrays a partir dele. -For instance, for `[-1, 2, 3, -9, 11]`: +Por exemplo, para `[-1, 2, 3, -9, 11]`: ```js no-beautify -// Starting from -1: +// Começando a partir de -1: -1 -1 + 2 -1 + 2 + 3 -1 + 2 + 3 + (-9) -1 + 2 + 3 + (-9) + 11 -// Starting from 2: +// Começando a partir de 2: 2 2 + 3 2 + 3 + (-9) 2 + 3 + (-9) + 11 -// Starting from 3: +// Começando a partir de 3: 3 3 + (-9) 3 + (-9) + 11 -// Starting from -9 +// Começando a partir de -9 -9 -9 + 11 -// Starting from 11 +// Começando a partir de 11 11 ``` -The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element. +O código, na verdade, é um laço aninhado: o laço externo percorre os elementos do array, e o interno conta as somas parciais começando pelo elemento atual. ```js run function getMaxSubSum(arr) { - let maxSum = 0; // if we take no elements, zero will be returned + let maxSum = 0; // se não pegarmos nenhum elemento, zero será retornado for (let i = 0; i < arr.length; i++) { let sumFixedStart = 0; @@ -57,25 +57,25 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6 alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100 ``` -The solution has a time complexity of [O(n2)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer. +A solução tem complexidade de tempo [O(n2)](https://en.wikipedia.org/wiki/Big_O_notation). Em outras palavras, se aumentarmos o tamanho do array 2 vezes, o algoritmo vai demorar 4 vezes mais. -For big arrays (1000, 10000 or more items) such algorithms can lead to serious sluggishness. +Para arrays grandes (1000, 10000 ou mais itens), algoritmos assim podem causar uma lentidão séria. -# Fast solution +# Solução rápida -Let's walk the array and keep the current partial sum of elements in the variable `s`. If `s` becomes negative at some point, then assign `s=0`. The maximum of all such `s` will be the answer. +Vamos percorrer o array e manter a soma parcial atual dos elementos na variável `s`. Se `s` se tornar negativa em algum momento, então atribuímos `s=0`. O maior valor entre todos esses `s` será a resposta. -If the description is too vague, please see the code, it's short enough: +Se a descrição estiver vaga demais, veja o código, ele é curto o suficiente: ```js run demo function getMaxSubSum(arr) { let maxSum = 0; let partialSum = 0; - for (let item of arr) { // for each item of arr - partialSum += item; // add it to partialSum - maxSum = Math.max(maxSum, partialSum); // remember the maximum - if (partialSum < 0) partialSum = 0; // zero if negative + for (let item of arr) { // para cada item de arr + partialSum += item; // adiciona ele ao partialSum + maxSum = Math.max(maxSum, partialSum); // guarda o máximo + if (partialSum < 0) partialSum = 0; // zera se for negativo } return maxSum; @@ -89,6 +89,6 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6 alert( getMaxSubSum([-1, -2, -3]) ); // 0 ``` -The algorithm requires exactly 1 array pass, so the time complexity is O(n). +O algoritmo exige exatamente 1 passagem pelo array, então a complexidade de tempo é O(n). -You can find more detailed information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words. +Você pode encontrar informações mais detalhadas sobre o algoritmo aqui: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). Se ainda não estiver óbvio por que isso funciona, tente rastrear o algoritmo nos exemplos acima, veja como ele funciona, isso é melhor do que qualquer explicação. diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/task.md b/1-js/05-data-types/04-array/10-maximal-subarray/task.md index f1a1d9f95..57e262a1f 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/task.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/task.md @@ -2,29 +2,29 @@ importance: 2 --- -# A maximal subarray +# Um subarray máximo -The input is an array of numbers, e.g. `arr = [1, -2, 3, 4, -9, 6]`. +A entrada é um array de números, ex.: `arr = [1, -2, 3, 4, -9, 6]`. -The task is: find the contiguous subarray of `arr` with the maximal sum of items. +A tarefa é: encontrar o subarray contíguo de `arr` com a maior soma de itens. -Write the function `getMaxSubSum(arr)` that will return that sum. +Escreva a função `getMaxSubSum(arr)` que retornará essa soma. -For instance: +Por exemplo: ```js -getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (the sum of highlighted items) +getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (a soma dos itens destacados) getMaxSubSum([*!*2, -1, 2, 3*/!*, -9]) == 6 getMaxSubSum([-1, 2, 3, -9, *!*11*/!*]) == 11 getMaxSubSum([-2, -1, *!*1, 2*/!*]) == 3 getMaxSubSum([*!*100*/!*, -9, 2, -3, 5]) == 100 -getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (take all) +getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (pega todos) ``` -If all items are negative, it means that we take none (the subarray is empty), so the sum is zero: +Se todos os itens forem negativos, significa que não pegamos nenhum (o subarray está vazio), então a soma é zero: ```js getMaxSubSum([-1, -2, -3]) = 0 ``` -Please try to think of a fast solution: [O(n2)](https://en.wikipedia.org/wiki/Big_O_notation) or even O(n) if you can. +Tente pensar numa solução rápida: [O(n2)](https://en.wikipedia.org/wiki/Big_O_notation) ou até O(n), se conseguir. diff --git a/1-js/05-data-types/04-array/2-create-array/task.md b/1-js/05-data-types/04-array/2-create-array/task.md index d4551c79c..a36fa6995 100644 --- a/1-js/05-data-types/04-array/2-create-array/task.md +++ b/1-js/05-data-types/04-array/2-create-array/task.md @@ -2,17 +2,17 @@ importance: 5 --- -# Array operations. +# Operações com array. -Let's try 5 array operations. +Vamos tentar 5 operações com array. -1. Create an array `styles` with items "Jazz" and "Blues". -2. Append "Rock-n-Roll" to the end. -3. Replace the value in the middle with "Classics". Your code for finding the middle value should work for any arrays with odd length. -4. Strip off the first value of the array and show it. -5. Prepend `Rap` and `Reggae` to the array. +1. Crie um array `styles` com os itens "Jazz" e "Blues". +2. Acrescente "Rock-n-Roll" ao final. +3. Substitua o valor do meio por "Classics". Seu código para encontrar o valor do meio deve funcionar para qualquer array de tamanho ímpar. +4. Remova o primeiro valor do array e mostre-o. +5. Adicione `Rap` e `Reggae` no início do array. -The array in the process: +O array durante o processo: ```js no-beautify Jazz, Blues diff --git a/1-js/05-data-types/04-array/3-call-array-this/solution.md b/1-js/05-data-types/04-array/3-call-array-this/solution.md index 3cb0317cf..55d273e7d 100644 --- a/1-js/05-data-types/04-array/3-call-array-this/solution.md +++ b/1-js/05-data-types/04-array/3-call-array-this/solution.md @@ -1,6 +1,6 @@ -The call `arr[2]()` is syntactically the good old `obj[method]()`, in the role of `obj` we have `arr`, and in the role of `method` we have `2`. +A chamada `arr[2]()` é, sintaticamente, o bom e velho `obj[method]()`, no papel de `obj` temos `arr`, e no papel de `method` temos `2`. -So we have a call of the function `arr[2]` as an object method. Naturally, it receives `this` referencing the object `arr` and outputs the array: +Então temos uma chamada da função `arr[2]` como um método de objeto. Naturalmente, ela recebe `this` referenciando o objeto `arr` e exibe o array: ```js run let arr = ["a", "b"]; @@ -12,4 +12,4 @@ arr.push(function() { arr[2](); // a,b,function(){...} ``` -The array has 3 values: initially it had two, plus the function. +O array tem 3 valores: inicialmente tinha dois, mais a função. diff --git a/1-js/05-data-types/04-array/3-call-array-this/task.md b/1-js/05-data-types/04-array/3-call-array-this/task.md index f1e13499c..f10b222f0 100644 --- a/1-js/05-data-types/04-array/3-call-array-this/task.md +++ b/1-js/05-data-types/04-array/3-call-array-this/task.md @@ -2,9 +2,9 @@ importance: 5 --- -# Calling in an array context +# Chamando no contexto de um array -What is the result? Why? +Qual é o resultado? Por quê? ```js let arr = ["a", "b"]; diff --git a/1-js/05-data-types/04-array/5-array-input-sum/solution.md b/1-js/05-data-types/04-array/5-array-input-sum/solution.md index 75bd683b5..88ebc0406 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/solution.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/solution.md @@ -1,4 +1,4 @@ -Please note the subtle, but important detail of the solution. We don't convert `value` to number instantly after `prompt`, because after `value = +value` we would not be able to tell an empty string (stop sign) from the zero (valid number). We do it later instead. +Observe o detalhe sutil, mas importante, da solução. Não convertemos `value` para número logo depois do `prompt`, porque depois de `value = +value` não conseguiríamos mais distinguir uma string vazia (sinal de parada) do zero (número válido). Fazemos isso mais tarde, em vez disso. ```js run demo @@ -8,9 +8,9 @@ function sumInput() { while (true) { - let value = prompt("A number please?", 0); + let value = prompt("Um número, por favor?", 0); - // should we cancel? + // devemos cancelar? if (value === "" || value === null || !isFinite(value)) break; numbers.push(+value); diff --git a/1-js/05-data-types/04-array/5-array-input-sum/task.md b/1-js/05-data-types/04-array/5-array-input-sum/task.md index 4af8e7c95..4e903dc20 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/task.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/task.md @@ -2,14 +2,14 @@ importance: 4 --- -# Sum input numbers +# Soma os números digitados -Write the function `sumInput()` that: +Escreva a função `sumInput()` que: -- Asks the user for values using `prompt` and stores the values in the array. -- Finishes asking when the user enters a non-numeric value, an empty string, or presses "Cancel". -- Calculates and returns the sum of array items. +- Pede valores ao usuário usando `prompt` e armazena os valores no array. +- Para de pedir quando o usuário digita um valor não numérico, uma string vazia, ou clica em "Cancelar". +- Calcula e retorna a soma dos itens do array. -P.S. A zero `0` is a valid number, please don't stop the input on zero. +P.S. Um zero `0` é um número válido, por favor não pare a entrada ao receber zero. [demo] diff --git a/1-js/05-data-types/04-array/array-pop.svg b/1-js/05-data-types/04-array/array-pop.svg index 82b112b4a..9d38b226a 100644 --- a/1-js/05-data-types/04-array/array-pop.svg +++ b/1-js/05-data-types/04-array/array-pop.svg @@ -1 +1 @@ -0123"Apple""Orange""Pear""Lemon"length = 4clear012"Apple""Orange""Pear"length = 3 \ No newline at end of file +0123"Apple""Orange""Pear""Lemon"length = 4limpar012"Apple""Orange""Pear"length = 3 \ No newline at end of file diff --git a/1-js/05-data-types/04-array/array-shift.svg b/1-js/05-data-types/04-array/array-shift.svg index 9485a3c96..fb80481c6 100644 --- a/1-js/05-data-types/04-array/array-shift.svg +++ b/1-js/05-data-types/04-array/array-shift.svg @@ -1 +1 @@ -123"Orange""Pear""Lemon"length = 423"Orange""Pear""Lemon"length = 3clearmove elements to the left0"Apple"012"Orange""Pear""Lemon"11 \ No newline at end of file +123"Orange""Pear""Lemon"length = 423"Orange""Pear""Lemon"length = 3limparmover elementos para a esquerda0"Apple"012"Orange""Pear""Lemon"11 \ No newline at end of file diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 6a5d8ecdb..4caabd33c 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -1,31 +1,31 @@ # Arrays -Objects allow you to store keyed collections of values. That's fine. +Objetos permitem armazenar coleções de valores indexadas por chave. Isso é ótimo. -But quite often we find that we need an *ordered collection*, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc. +Mas, frequentemente, percebemos que precisamos de uma *coleção ordenada*, onde temos um 1º, um 2º, um 3º elemento e assim por diante. Por exemplo, precisamos disso para armazenar uma lista de algo: usuários, produtos, elementos HTML etc. -It is not convenient to use an object here, because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use. +Não é conveniente usar um objeto aqui, porque ele não oferece métodos para gerenciar a ordem dos elementos. Não podemos inserir uma nova propriedade "entre" as existentes. Objetos simplesmente não servem para esse tipo de uso. -There exists a special data structure named `Array`, to store ordered collections. +Existe uma estrutura de dados especial chamada `Array`, para armazenar coleções ordenadas. -## Declaration +## Declaração -There are two syntaxes for creating an empty array: +Existem duas sintaxes para criar um array vazio: ```js let arr = new Array(); let arr = []; ``` -Almost all the time, the second syntax is used. We can supply initial elements in the brackets: +Quase sempre, a segunda sintaxe é usada. Podemos informar os elementos iniciais entre colchetes: ```js let fruits = ["Apple", "Orange", "Plum"]; ``` -Array elements are numbered, starting with zero. +Os elementos do array são numerados, começando do zero. -We can get an element by its number in square brackets: +Podemos obter um elemento pelo seu número entre colchetes: ```js run let fruits = ["Apple", "Orange", "Plum"]; @@ -35,19 +35,19 @@ alert( fruits[1] ); // Orange alert( fruits[2] ); // Plum ``` -We can replace an element: +Podemos substituir um elemento: ```js -fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"] +fruits[2] = 'Pear'; // agora ["Apple", "Orange", "Pear"] ``` -...Or add a new one to the array: +...Ou adicionar um novo ao array: ```js -fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"] +fruits[3] = 'Lemon'; // agora ["Apple", "Orange", "Pear", "Lemon"] ``` -The total count of the elements in the array is its `length`: +A contagem total de elementos no array é o seu `length`: ```js run let fruits = ["Apple", "Orange", "Plum"]; @@ -55,7 +55,7 @@ let fruits = ["Apple", "Orange", "Plum"]; alert( fruits.length ); // 3 ``` -We can also use `alert` to show the whole array. +Também podemos usar `alert` para mostrar o array inteiro. ```js run let fruits = ["Apple", "Orange", "Plum"]; @@ -63,24 +63,24 @@ let fruits = ["Apple", "Orange", "Plum"]; alert( fruits ); // Apple,Orange,Plum ``` -An array can store elements of any type. +Um array pode armazenar elementos de qualquer tipo. -For instance: +Por exemplo: ```js run no-beautify -// mix of values +// mistura de valores let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ]; -// get the object at index 1 and then show its name +// pega o objeto no índice 1 e depois mostra seu name alert( arr[1].name ); // John -// get the function at index 3 and run it +// pega a função no índice 3 e a executa arr[3](); // hello ``` -````smart header="Trailing comma" -An array, just like an object, may end with a comma: +````smart header="Vírgula no final" +Um array, assim como um objeto, pode terminar com uma vírgula: ```js let fruits = [ "Apple", @@ -89,20 +89,20 @@ let fruits = [ ]; ``` -The "trailing comma" style makes it easier to insert/remove items, because all lines become alike. +O estilo de "vírgula no final" facilita inserir/remover itens, porque todas as linhas ficam parecidas. ```` -## Get last elements with "at" +## Obtendo os últimos elementos com "at" [recent browser="new"] -Let's say we want the last element of the array. +Digamos que queremos o último elemento do array. -Some programming languages allow to use negative indexes for the same purpose, like `fruits[-1]`. +Algumas linguagens de programação permitem usar índices negativos para esse mesmo propósito, como `fruits[-1]`. -Although, in JavaScript it won't work. The result will be `undefined`, because the index in square brackets is treated literally. +Porém, no JavaScript isso não funciona. O resultado vai ser `undefined`, porque o índice entre colchetes é tratado literalmente. -We can explicitly calculate the last element index and then access it: `fruits[fruits.length - 1]`. +Podemos calcular explicitamente o índice do último elemento e então acessá-lo: `fruits[fruits.length - 1]`. ```js run let fruits = ["Apple", "Orange", "Plum"]; @@ -110,70 +110,70 @@ let fruits = ["Apple", "Orange", "Plum"]; alert( fruits[fruits.length-1] ); // Plum ``` -A bit cumbersome, isn't it? We need to write the variable name twice. +Um pouco incômodo, não é mesmo? Precisamos escrever o nome da variável duas vezes. -Luckily, there's a shorter syntax: `fruits.at(-1)`: +Felizmente, existe uma sintaxe mais curta: `fruits.at(-1)`: ```js run let fruits = ["Apple", "Orange", "Plum"]; -// same as fruits[fruits.length-1] +// o mesmo que fruits[fruits.length-1] alert( fruits.at(-1) ); // Plum ``` -In other words, `arr.at(i)`: -- is exactly the same as `arr[i]`, if `i >= 0`. -- for negative values of `i`, it steps back from the end of the array. +Em outras palavras, `arr.at(i)`: +- é exatamente igual a `arr[i]`, se `i >= 0`. +- para valores negativos de `i`, ele volta a partir do final do array. -## Methods pop/push, shift/unshift +## Métodos pop/push, shift/unshift -A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is one of the most common uses of an array. In computer science, this means an ordered collection of elements which supports two operations: +Uma [fila](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) é um dos usos mais comuns de um array. Em ciência da computação, isso significa uma coleção ordenada de elementos que suporta duas operações: -- `push` appends an element to the end. -- `shift` get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st. +- `push` acrescenta um elemento ao final. +- `shift` pega um elemento do início, avançando a fila, de forma que o 2º elemento se torna o 1º. ![](queue.svg) -Arrays support both operations. +Arrays suportam as duas operações. -In practice we need it very often. For example, a queue of messages that need to be shown on-screen. +Na prática, precisamos disso com bastante frequência. Por exemplo, uma fila de mensagens que precisam ser mostradas na tela. -There's another use case for arrays -- the data structure named [stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)). +Existe outro caso de uso para arrays -- a estrutura de dados chamada [pilha](https://pt.wikipedia.org/wiki/Pilha_(estrutura_de_dados)). -It supports two operations: +Ela suporta duas operações: -- `push` adds an element to the end. -- `pop` takes an element from the end. +- `push` adiciona um elemento ao final. +- `pop` pega um elemento do final. -So new elements are added or taken always from the "end". +Então novos elementos são sempre adicionados ou retirados do "final". -A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from the top: +Uma pilha geralmente é ilustrada como um maço de cartas: novas cartas são adicionadas ao topo ou retiradas do topo: ![](stack.svg) -For stacks, the latest pushed item is received first, that's also called LIFO (Last-In-First-Out) principle. For queues, we have FIFO (First-In-First-Out). +Para pilhas, o último item empilhado é o primeiro a ser recebido, isso também é chamado de princípio LIFO (*Last-In-First-Out*, "último a entrar, primeiro a sair"). Para filas, temos o FIFO (*First-In-First-Out*, "primeiro a entrar, primeiro a sair"). -Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements, both to/from the beginning or the end. +Arrays no JavaScript podem funcionar tanto como fila quanto como pilha. Eles permitem adicionar/remover elementos, tanto do início quanto do final. -In computer science, the data structure that allows this, is called [deque](https://en.wikipedia.org/wiki/Double-ended_queue). +Em ciência da computação, a estrutura de dados que permite isso é chamada de [deque](https://pt.wikipedia.org/wiki/Deque_(estruturas_de_dados)). -**Methods that work with the end of the array:** +**Métodos que trabalham com o final do array:** `pop` -: Extracts the last element of the array and returns it: +: Extrai o último elemento do array e o retorna: ```js run let fruits = ["Apple", "Orange", "Pear"]; - alert( fruits.pop() ); // remove "Pear" and alert it + alert( fruits.pop() ); // remove "Pear" e o exibe alert( fruits ); // Apple, Orange ``` - Both `fruits.pop()` and `fruits.at(-1)` return the last element of the array, but `fruits.pop()` also modifies the array by removing it. + Tanto `fruits.pop()` quanto `fruits.at(-1)` retornam o último elemento do array, mas `fruits.pop()` também modifica o array, removendo-o. `push` -: Append the element to the end of the array: +: Acrescenta o elemento ao final do array: ```js run let fruits = ["Apple", "Orange"]; @@ -183,23 +183,23 @@ In computer science, the data structure that allows this, is called [deque](http alert( fruits ); // Apple, Orange, Pear ``` - The call `fruits.push(...)` is equal to `fruits[fruits.length] = ...`. + A chamada `fruits.push(...)` equivale a `fruits[fruits.length] = ...`. -**Methods that work with the beginning of the array:** +**Métodos que trabalham com o início do array:** `shift` -: Extracts the first element of the array and returns it: +: Extrai o primeiro elemento do array e o retorna: ```js run let fruits = ["Apple", "Orange", "Pear"]; - alert( fruits.shift() ); // remove Apple and alert it + alert( fruits.shift() ); // remove Apple e o exibe alert( fruits ); // Orange, Pear ``` `unshift` -: Add the element to the beginning of the array: +: Adiciona o elemento ao início do array: ```js run let fruits = ["Orange", "Pear"]; @@ -209,7 +209,7 @@ In computer science, the data structure that allows this, is called [deque](http alert( fruits ); // Apple, Orange, Pear ``` -Methods `push` and `unshift` can add multiple elements at once: +Os métodos `push` e `unshift` podem adicionar vários elementos de uma vez: ```js run let fruits = ["Apple"]; @@ -221,97 +221,97 @@ fruits.unshift("Pineapple", "Lemon"); alert( fruits ); ``` -## Internals +## Por dentro -An array is a special kind of object. The square brackets used to access a property `arr[0]` actually come from the object syntax. That's essentially the same as `obj[key]`, where `arr` is the object, while numbers are used as keys. +Um array é um tipo especial de objeto. Os colchetes usados para acessar uma propriedade, `arr[0]`, na verdade vêm da sintaxe de objeto. Isso é essencialmente igual a `obj[key]`, onde `arr` é o objeto, e números são usados como chaves. -They extend objects providing special methods to work with ordered collections of data and also the `length` property. But at the core it's still an object. +Eles estendem os objetos, oferecendo métodos especiais para trabalhar com coleções ordenadas de dados e também a propriedade `length`. Mas, no fundo, ainda é um objeto. -Remember, there are only eight basic data types in JavaScript (see the [Data types](info:types) chapter for more info). Array is an object and thus behaves like an object. +Lembre-se, existem apenas oito tipos de dados básicos no JavaScript (veja o capítulo [Tipos de dados](info:types) para mais informações). Array é um objeto e, portanto, se comporta como um objeto. -For instance, it is copied by reference: +Por exemplo, ele é copiado por referência: ```js run let fruits = ["Banana"] -let arr = fruits; // copy by reference (two variables reference the same array) +let arr = fruits; // cópia por referência (duas variáveis referenciam o mesmo array) alert( arr === fruits ); // true -arr.push("Pear"); // modify the array by reference +arr.push("Pear"); // modifica o array por referência -alert( fruits ); // Banana, Pear - 2 items now +alert( fruits ); // Banana, Pear - 2 itens agora ``` -...But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast. +...Mas o que torna os arrays realmente especiais é sua representação interna. O motor tenta armazenar seus elementos numa área contígua de memória, um após o outro, exatamente como mostrado nas ilustrações deste capítulo, e existem outras otimizações também, para fazer os arrays funcionarem bem rápido. -But they all break if we quit working with an array as with an "ordered collection" and start working with it as if it were a regular object. +Mas tudo isso para de funcionar se deixarmos de trabalhar com um array como uma "coleção ordenada" e começarmos a trabalhar com ele como se fosse um objeto comum. -For instance, technically we can do this: +Por exemplo, tecnicamente podemos fazer isto: ```js -let fruits = []; // make an array +let fruits = []; // cria um array -fruits[99999] = 5; // assign a property with the index far greater than its length +fruits[99999] = 5; // atribui uma propriedade com um índice bem maior que seu length -fruits.age = 25; // create a property with an arbitrary name +fruits.age = 25; // cria uma propriedade com um nome arbitrário ``` -That's possible, because arrays are objects at their base. We can add any properties to them. +Isso é possível, porque arrays são objetos em sua base. Podemos adicionar qualquer propriedade a eles. -But the engine will see that we're working with the array as with a regular object. Array-specific optimizations are not suited for such cases and will be turned off, their benefits disappear. +Mas o motor vai perceber que estamos trabalhando com o array como se fosse um objeto comum. As otimizações específicas de array não são adequadas para esses casos e serão desativadas, seus benefícios desaparecem. -The ways to misuse an array: +Formas de usar um array incorretamente: -- Add a non-numeric property like `arr.test = 5`. -- Make holes, like: add `arr[0]` and then `arr[1000]` (and nothing between them). -- Fill the array in the reverse order, like `arr[1000]`, `arr[999]` and so on. +- Adicionar uma propriedade não numérica, como `arr.test = 5`. +- Criar buracos, tipo: adicionar `arr[0]` e depois `arr[1000]` (e nada entre eles). +- Preencher o array na ordem reversa, tipo `arr[1000]`, `arr[999]` e assim por diante. -Please think of arrays as special structures to work with the *ordered data*. They provide special methods for that. Arrays are carefully tuned inside JavaScript engines to work with contiguous ordered data, please use them this way. And if you need arbitrary keys, chances are high that you actually require a regular object `{}`. +Pense nos arrays como estruturas especiais para trabalhar com *dados ordenados*. Eles oferecem métodos especiais para isso. Os arrays são cuidadosamente ajustados dentro dos motores do JavaScript para trabalhar com dados ordenados e contíguos, por favor, use-os dessa forma. E se você precisar de chaves arbitrárias, é bem provável que você precise, na verdade, de um objeto comum `{}`. -## Performance +## Desempenho -Methods `push/pop` run fast, while `shift/unshift` are slow. +Os métodos `push/pop` são rápidos, enquanto `shift/unshift` são lentos. ![](array-speed.svg) -Why is it faster to work with the end of an array than with its beginning? Let's see what happens during the execution: +Por que é mais rápido trabalhar com o final de um array do que com seu início? Vamos ver o que acontece durante a execução: ```js -fruits.shift(); // take 1 element from the start +fruits.shift(); // pega 1 elemento do início ``` -It's not enough to take and remove the element with the index `0`. Other elements need to be renumbered as well. +Não basta pegar e remover o elemento com o índice `0`. Os outros elementos também precisam ser renumerados. -The `shift` operation must do 3 things: +A operação `shift` precisa fazer 3 coisas: -1. Remove the element with the index `0`. -2. Move all elements to the left, renumber them from the index `1` to `0`, from `2` to `1` and so on. -3. Update the `length` property. +1. Remover o elemento com o índice `0`. +2. Mover todos os elementos para a esquerda, renumerando-os do índice `1` para `0`, de `2` para `1` e assim por diante. +3. Atualizar a propriedade `length`. ![](array-shift.svg) -**The more elements in the array, the more time to move them, more in-memory operations.** +**Quanto mais elementos no array, mais tempo leva para movê-los, mais operações em memória.** -The similar thing happens with `unshift`: to add an element to the beginning of the array, we need first to move existing elements to the right, increasing their indexes. +Algo parecido acontece com `unshift`: para adicionar um elemento ao início do array, primeiro precisamos mover os elementos existentes para a direita, aumentando seus índices. -And what's with `push/pop`? They do not need to move anything. To extract an element from the end, the `pop` method cleans the index and shortens `length`. +E o que acontece com `push/pop`? Eles não precisam mover nada. Para extrair um elemento do final, o método `pop` limpa o índice e reduz o `length`. -The actions for the `pop` operation: +As ações da operação `pop`: ```js -fruits.pop(); // take 1 element from the end +fruits.pop(); // pega 1 elemento do final ``` ![](array-pop.svg) -**The `pop` method does not need to move anything, because other elements keep their indexes. That's why it's blazingly fast.** +**O método `pop` não precisa mover nada, porque os outros elementos mantêm seus índices. É por isso que ele é extremamente rápido.** -The similar thing with the `push` method. +O mesmo vale para o método `push`. -## Loops +## Laços -One of the oldest ways to cycle array items is the `for` loop over indexes: +Uma das formas mais antigas de percorrer os itens de um array é o laço `for` sobre os índices: ```js run let arr = ["Apple", "Orange", "Pear"]; @@ -323,20 +323,20 @@ for (let i = 0; i < arr.length; i++) { } ``` -But for arrays there is another form of loop, `for..of`: +Mas, para arrays, existe outra forma de laço, o `for..of`: ```js run let fruits = ["Apple", "Orange", "Plum"]; -// iterates over array elements +// itera sobre os elementos do array for (let fruit of fruits) { alert( fruit ); } ``` -The `for..of` doesn't give access to the number of the current element, just its value, but in most cases that's enough. And it's shorter. +O `for..of` não dá acesso ao número do elemento atual, só ao seu valor, mas, na maioria dos casos, isso é suficiente. E é mais curto. -Technically, because arrays are objects, it is also possible to use `for..in`: +Tecnicamente, como arrays são objetos, também é possível usar `for..in`: ```js run let arr = ["Apple", "Orange", "Pear"]; @@ -348,22 +348,22 @@ for (let key in arr) { } ``` -But that's actually a bad idea. There are potential problems with it: +Mas isso na verdade é uma má ideia. Existem problemas em potencial com isso: -1. The loop `for..in` iterates over *all properties*, not only the numeric ones. +1. O laço `for..in` itera sobre *todas as propriedades*, não só as numéricas. - There are so-called "array-like" objects in the browser and in other environments, that *look like arrays*. That is, they have `length` and indexes properties, but they may also have other non-numeric properties and methods, which we usually don't need. The `for..in` loop will list them though. So if we need to work with array-like objects, then these "extra" properties can become a problem. + Existem os chamados objetos "semelhantes a array" no navegador e em outros ambientes, que *parecem arrays*. Ou seja, eles têm propriedades `length` e índices, mas também podem ter outras propriedades e métodos não numéricos, dos quais normalmente não precisamos. O laço `for..in`, porém, vai listá-los também. Então, se precisarmos trabalhar com objetos semelhantes a array, essas propriedades "extras" podem se tornar um problema. -2. The `for..in` loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it's still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference. +2. O laço `for..in` é otimizado para objetos genéricos, não para arrays, e por isso é de 10 a 100 vezes mais lento. Claro, ainda é bem rápido. A diferença de velocidade só costuma importar em gargalos. Mas, mesmo assim, devemos estar cientes dessa diferença. -Generally, we shouldn't use `for..in` for arrays. +De modo geral, não devemos usar `for..in` para arrays. -## A word about "length" +## Uma palavra sobre "length" -The `length` property automatically updates when we modify the array. To be precise, it is actually not the count of values in the array, but the greatest numeric index plus one. +A propriedade `length` se atualiza automaticamente quando modificamos o array. Para ser mais preciso, na verdade ela não é a contagem de valores no array, mas sim o maior índice numérico mais um. -For instance, a single element with a large index gives a big length: +Por exemplo, um único elemento com um índice grande gera um length grande: ```js run let fruits = []; @@ -372,52 +372,52 @@ fruits[123] = "Apple"; alert( fruits.length ); // 124 ``` -Note that we usually don't use arrays like that. +Observe que normalmente não usamos arrays dessa forma. -Another interesting thing about the `length` property is that it's writable. +Outra coisa interessante sobre a propriedade `length` é que ela é gravável. -If we increase it manually, nothing interesting happens. But if we decrease it, the array is truncated. The process is irreversible, here's the example: +Se a aumentarmos manualmente, nada de interessante acontece. Mas se a diminuirmos, o array é truncado. O processo é irreversível, aqui está o exemplo: ```js run let arr = [1, 2, 3, 4, 5]; -arr.length = 2; // truncate to 2 elements +arr.length = 2; // trunca para 2 elementos alert( arr ); // [1, 2] -arr.length = 5; // return length back -alert( arr[3] ); // undefined: the values do not return +arr.length = 5; // retorna o length de volta +alert( arr[3] ); // undefined: os valores não voltam ``` -So, the simplest way to clear the array is: `arr.length = 0;`. +Então, a forma mais simples de limpar o array é: `arr.length = 0;`. ## new Array() [#new-array] -There is one more syntax to create an array: +Existe mais uma sintaxe para criar um array: ```js let arr = *!*new Array*/!*("Apple", "Pear", "etc"); ``` -It's rarely used, because square brackets `[]` are shorter. Also, there's a tricky feature with it. +É raramente usada, porque os colchetes `[]` são mais curtos. Além disso, há uma peculiaridade nela. -If `new Array` is called with a single argument which is a number, then it creates an array *without items, but with the given length*. +Se `new Array` for chamado com um único argumento que seja um número, então ele cria um array *sem itens, mas com o length dado*. -Let's see how one can shoot themselves in the foot: +Vamos ver como alguém pode atirar no próprio pé: ```js run -let arr = new Array(2); // will it create an array of [2] ? +let arr = new Array(2); // será que isso cria um array [2] ? -alert( arr[0] ); // undefined! no elements. +alert( arr[0] ); // undefined! sem elementos. alert( arr.length ); // length 2 ``` -To avoid such surprises, we usually use square brackets, unless we really know what we're doing. +Para evitar essas surpresas, normalmente usamos os colchetes, a menos que realmente saibamos o que estamos fazendo. -## Multidimensional arrays +## Arrays multidimensionais -Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices: +Arrays podem ter itens que também são arrays. Podemos usar isso para arrays multidimensionais, por exemplo, para armazenar matrizes: ```js run let matrix = [ @@ -426,14 +426,14 @@ let matrix = [ [7, 8, 9] ]; -alert( matrix[0][1] ); // 2, the second value of the first inner array +alert( matrix[0][1] ); // 2, o segundo valor do primeiro array interno ``` ## toString -Arrays have their own implementation of `toString` method that returns a comma-separated list of elements. +Arrays têm sua própria implementação do método `toString`, que retorna uma lista de elementos separados por vírgula. -For instance: +Por exemplo: ```js run @@ -443,7 +443,7 @@ alert( arr ); // 1,2,3 alert( String(arr) === '1,2,3' ); // true ``` -Also, let's try this: +Além disso, vamos tentar isto: ```js run alert( [] + 1 ); // "1" @@ -451,9 +451,9 @@ alert( [1] + 1 ); // "11" alert( [1,2] + 1 ); // "1,21" ``` -Arrays do not have `Symbol.toPrimitive`, neither a viable `valueOf`, they implement only `toString` conversion, so here `[]` becomes an empty string, `[1]` becomes `"1"` and `[1,2]` becomes `"1,2"`. +Arrays não têm `Symbol.toPrimitive`, nem um `valueOf` viável, eles implementam apenas a conversão `toString`, então aqui `[]` se torna uma string vazia, `[1]` se torna `"1"` e `[1,2]` se torna `"1,2"`. -When the binary plus `"+"` operator adds something to a string, it converts it to a string as well, so the next step looks like this: +Quando o operador de adição binário `"+"` soma algo a uma string, ele também converte isso para uma string, então o próximo passo fica assim: ```js run alert( "" + 1 ); // "1" @@ -461,31 +461,31 @@ alert( "1" + 1 ); // "11" alert( "1,2" + 1 ); // "1,21" ``` -## Don't compare arrays with == +## Não compare arrays com == -Arrays in JavaScript, unlike some other programming languages, shouldn't be compared with operator `==`. +Arrays no JavaScript, diferente de outras linguagens de programação, não devem ser comparados com o operador `==`. -This operator has no special treatment for arrays, it works with them as with any objects. +Esse operador não tem nenhum tratamento especial para arrays, ele funciona com eles como com qualquer objeto. -Let's recall the rules: +Vamos relembrar as regras: -- Two objects are equal `==` only if they're references to the same object. -- If one of the arguments of `==` is an object, and the other one is a primitive, then the object gets converted to primitive, as explained in the chapter . -- ...With an exception of `null` and `undefined` that equal `==` each other and nothing else. +- Dois objetos são iguais com `==` apenas se forem referências ao mesmo objeto. +- Se um dos argumentos de `==` for um objeto, e o outro for um primitivo, então o objeto é convertido para primitivo, como explicado no capítulo . +- ...Com exceção de `null` e `undefined`, que são iguais com `==` um ao outro e a mais nada. -The strict comparison `===` is even simpler, as it doesn't convert types. +A comparação estrita `===` é ainda mais simples, já que ela não converte tipos. -So, if we compare arrays with `==`, they are never the same, unless we compare two variables that reference exactly the same array. +Então, se compararmos arrays com `==`, eles nunca serão os mesmos, a menos que comparemos duas variáveis que referenciam exatamente o mesmo array. -For example: +Por exemplo: ```js run alert( [] == [] ); // false alert( [0] == [0] ); // false ``` -These arrays are technically different objects. So they aren't equal. The `==` operator doesn't do item-by-item comparison. +Esses arrays são, tecnicamente, objetos diferentes. Então eles não são iguais. O operador `==` não faz uma comparação item por item. -Comparison with primitives may give seemingly strange results as well: +A comparação com primitivos também pode dar resultados aparentemente estranhos: ```js run alert( 0 == [] ); // true @@ -493,59 +493,59 @@ alert( 0 == [] ); // true alert('0' == [] ); // false ``` -Here, in both cases, we compare a primitive with an array object. So the array `[]` gets converted to primitive for the purpose of comparison and becomes an empty string `''`. +Aqui, nos dois casos, estamos comparando um primitivo com um objeto array. Então o array `[]` é convertido para primitivo para fins de comparação e se torna uma string vazia `''`. -Then the comparison process goes on with the primitives, as described in the chapter : +Então o processo de comparação continua com os primitivos, como descrito no capítulo : ```js run -// after [] was converted to '' -alert( 0 == '' ); // true, as '' becomes converted to number 0 +// depois que [] foi convertido para '' +alert( 0 == '' ); // true, já que '' é convertido para o número 0 -alert('0' == '' ); // false, no type conversion, different strings +alert('0' == '' ); // false, sem conversão de tipo, strings diferentes ``` -So, how to compare arrays? +Então, como comparar arrays? -That's simple: don't use the `==` operator. Instead, compare them item-by-item in a loop or using iteration methods explained in the next chapter. +É simples: não use o operador `==`. Em vez disso, compare-os item por item num laço ou usando os métodos de iteração explicados no próximo capítulo. -## Summary +## Resumo -Array is a special kind of object, suited to storing and managing ordered data items. +Array é um tipo especial de objeto, adequado para armazenar e gerenciar itens de dados ordenados. -The declaration: +A declaração: ```js -// square brackets (usual) +// colchetes (usual) let arr = [item1, item2...]; -// new Array (exceptionally rare) +// new Array (excepcionalmente raro) let arr = new Array(item1, item2...); ``` -The call to `new Array(number)` creates an array with the given length, but without elements. +A chamada `new Array(number)` cria um array com o length dado, mas sem elementos. -- The `length` property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods. -- If we shorten `length` manually, the array is truncated. +- A propriedade `length` é o comprimento do array ou, para ser mais preciso, seu último índice numérico mais um. Ela é ajustada automaticamente pelos métodos de array. +- Se diminuirmos o `length` manualmente, o array é truncado. -Getting the elements: +Obtendo os elementos: -- we can get element by its index, like `arr[0]` -- also we can use `at(i)` method that allows negative indexes. For negative values of `i`, it steps back from the end of the array. If `i >= 0`, it works same as `arr[i]`. +- podemos obter um elemento pelo seu índice, como `arr[0]` +- também podemos usar o método `at(i)`, que permite índices negativos. Para valores negativos de `i`, ele volta a partir do final do array. Se `i >= 0`, funciona igual a `arr[i]`. -We can use an array as a deque with the following operations: +Podemos usar um array como um deque com as seguintes operações: -- `push(...items)` adds `items` to the end. -- `pop()` removes the element from the end and returns it. -- `shift()` removes the element from the beginning and returns it. -- `unshift(...items)` adds `items` to the beginning. +- `push(...items)` adiciona `items` ao final. +- `pop()` remove o elemento do final e o retorna. +- `shift()` remove o elemento do início e o retorna. +- `unshift(...items)` adiciona `items` ao início. -To loop over the elements of the array: - - `for (let i=0; i`, `<` and others), as they have no special treatment for arrays. They handle them as any objects, and it's not what we usually want. +Para comparar arrays, não use o operador `==` (nem `>`, `<` e outros), já que eles não têm nenhum tratamento especial para arrays. Eles os tratam como qualquer objeto, e não é isso que normalmente queremos. -Instead you can use `for..of` loop to compare arrays item-by-item. +Em vez disso, você pode usar o laço `for..of` para comparar arrays item por item. -We will continue with arrays and study more methods to add, remove, extract elements and sort arrays in the next chapter . +Vamos continuar com arrays e estudar mais métodos para adicionar, remover, extrair elementos e ordenar arrays no próximo capítulo . diff --git a/images.yml b/images.yml index d2f451e2a..b8cee36ab 100644 --- a/images.yml +++ b/images.yml @@ -78,3 +78,20 @@ promiseQueue.svg: "script execution finished": text: "execução do script terminada" position: left +array-pop.svg: + "clear": + text: "limpar" + position: center +array-shift.svg: + "clear": + text: "limpar" + position: center + "move": + text: "mover" + position: left + "elements": + text: "elementos" + position: left + "to the left": + text: "para a esquerda" + position: left From 377daa247de93c50eb0149d1af7cd3f01811874f Mon Sep 17 00:00:00 2001 From: Diogo Marciano Date: Sat, 21 Nov 2026 14:57:12 -0300 Subject: [PATCH 2/2] Apply review feedback from @gabifs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Revert the hand-edited array-pop.svg/array-shift.svg back to the original and regenerate them from images.yml via the gulp translation pipeline instead, per the project's standing rule of never hand-editing SVGs; verified visually that both render correctly - Add explicit anchor [#loops] to "## Laços" so the existing link from 02-first-steps/13-while-for keeps working - Fix dropped qualifier: "diferente de outras linguagens" (implies ALL others compare by value) -> "diferente de algumas outras linguagens" - Fix misleading comment: "retorna o length de volta" (sounds like it returns something) -> "restaura o length original" - Standardize informal "tipo" -> "como" (2 occurrences) - Standardize "somas parciais" -> "subsomas" in 10-maximal-subarray/solution.md to match the term used in _js.view/test.js, avoiding confusion with "soma parcial" (the `partialSum` accumulator, a different concept covered later in the same file) - Fix dangling "mais tarde, em vez disso" -> "em vez disso, fazemos isso mais tarde" Co-Authored-By: Claude Sonnet 5 --- .../04-array/10-maximal-subarray/solution.md | 4 ++-- .../04-array/5-array-input-sum/solution.md | 2 +- 1-js/05-data-types/04-array/article.md | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index 6c007a068..db1a8b6f6 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -1,6 +1,6 @@ # Solução lenta -Podemos calcular todas as somas parciais possíveis. +Podemos calcular todas as subsomas possíveis. A forma mais simples é pegar cada elemento e calcular as somas de todos os subarrays a partir dele. @@ -33,7 +33,7 @@ Por exemplo, para `[-1, 2, 3, -9, 11]`: 11 ``` -O código, na verdade, é um laço aninhado: o laço externo percorre os elementos do array, e o interno conta as somas parciais começando pelo elemento atual. +O código, na verdade, é um laço aninhado: o laço externo percorre os elementos do array, e o interno conta as subsomas começando pelo elemento atual. ```js run function getMaxSubSum(arr) { diff --git a/1-js/05-data-types/04-array/5-array-input-sum/solution.md b/1-js/05-data-types/04-array/5-array-input-sum/solution.md index 88ebc0406..ecafea3a5 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/solution.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/solution.md @@ -1,4 +1,4 @@ -Observe o detalhe sutil, mas importante, da solução. Não convertemos `value` para número logo depois do `prompt`, porque depois de `value = +value` não conseguiríamos mais distinguir uma string vazia (sinal de parada) do zero (número válido). Fazemos isso mais tarde, em vez disso. +Observe o detalhe sutil, mas importante, da solução. Não convertemos `value` para número logo depois do `prompt`, porque depois de `value = +value` não conseguiríamos mais distinguir uma string vazia (sinal de parada) do zero (número válido). Em vez disso, fazemos isso mais tarde. ```js run demo diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index 4caabd33c..348a7e71f 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -264,8 +264,8 @@ Mas o motor vai perceber que estamos trabalhando com o array como se fosse um ob Formas de usar um array incorretamente: - Adicionar uma propriedade não numérica, como `arr.test = 5`. -- Criar buracos, tipo: adicionar `arr[0]` e depois `arr[1000]` (e nada entre eles). -- Preencher o array na ordem reversa, tipo `arr[1000]`, `arr[999]` e assim por diante. +- Criar buracos, como adicionar `arr[0]` e depois `arr[1000]` (e nada entre eles). +- Preencher o array na ordem reversa, como `arr[1000]`, `arr[999]` e assim por diante. Pense nos arrays como estruturas especiais para trabalhar com *dados ordenados*. Eles oferecem métodos especiais para isso. Os arrays são cuidadosamente ajustados dentro dos motores do JavaScript para trabalhar com dados ordenados e contíguos, por favor, use-os dessa forma. E se você precisar de chaves arbitrárias, é bem provável que você precise, na verdade, de um objeto comum `{}`. @@ -309,7 +309,7 @@ fruits.pop(); // pega 1 elemento do final O mesmo vale para o método `push`. -## Laços +## Laços [#loops] Uma das formas mais antigas de percorrer os itens de um array é o laço `for` sobre os índices: @@ -384,7 +384,7 @@ let arr = [1, 2, 3, 4, 5]; arr.length = 2; // trunca para 2 elementos alert( arr ); // [1, 2] -arr.length = 5; // retorna o length de volta +arr.length = 5; // restaura o length original alert( arr[3] ); // undefined: os valores não voltam ``` @@ -463,7 +463,7 @@ alert( "1,2" + 1 ); // "1,21" ## Não compare arrays com == -Arrays no JavaScript, diferente de outras linguagens de programação, não devem ser comparados com o operador `==`. +Arrays no JavaScript, diferente de algumas outras linguagens de programação, não devem ser comparados com o operador `==`. Esse operador não tem nenhum tratamento especial para arrays, ele funciona com eles como com qualquer objeto.