chore: manual translations (#42811)

This commit is contained in:
Nicholas Carrigan (he/him)
2021-07-09 21:23:54 -07:00
committed by GitHub
parent a3395269a0
commit c4fd49e5b7
806 changed files with 8935 additions and 4378 deletions

View File

@ -1,6 +1,6 @@
---
id: 5a661e0f1068aca922b3ef17
title: Access an Array's Contents Using Bracket Notation
title: Acesse o Conteúdo de uma Lista Utilizando a Notação de Colchetes
challengeType: 1
forumTopicId: 301149
dashedName: access-an-arrays-contents-using-bracket-notation
@ -8,55 +8,55 @@ dashedName: access-an-arrays-contents-using-bracket-notation
# --description--
The fundamental feature of any data structure is, of course, the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.
A funcionalidade fundamental de qualquer estrutura de dados é, evidentemente, não só a capacidade de armazenar informação, como também a possibilidade de acessar esta informação quando necessário. Então, agora que aprendemos como criar um vetor, vamos começar a pensar em como podemos acessar as informações desse vetor.
When we define a simple array as seen below, there are 3 items in it:
Quando definimos uma matriz simples como vista abaixo, existem 3 itens nela:
```js
let ourArray = ["a", "b", "c"];
```
In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the ***zeroth*** position, not the first. In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>. For example, if we want to retrieve the `a` from `ourArray` and assign it to a variable, we can do so with the following code:
Em um array, cada item do array possui um <dfn>índice </dfn>. Esse índice possui dois papéis, é a posição daquele item no array e como você o referencia. No entanto, é importante notar que arrays em JavaScript são <dfn>indexados a zero</dfn>, o que significa que o primeiro elemento do array está, na verdade, na posição ***zero***, e não na primeira. Para recuperar um elemento de um array, nós podemos ao final de um array adicionar um índice encapsulado com colchetes (por exemplo [0]), ou mais comumente, no final de uma variável que faz referência a um objeto array. Isso é conhecido como <dfn>notação de colchetes</dfn>. Por exemplo, se queremos recuperar o `a` de um array `ourArray` e atribuir a uma variável, nós podemos fazer isso com o código a seguir:
```js
let ourVariable = ourArray[0];
```
Now `ourVariable` has the value of `a`.
Agora `ourVariable` possui o valor de `a`.
In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:
Além de acessar o valor associado ao índice, você também pode *definir* um índice para um valor usando a mesma notação:
```js
ourArray[1] = "not b anymore";
```
Using bracket notation, we have now reset the item at index 1 from the string `b`, to `not b anymore`. Now `ourArray` is `["a", "not b anymore", "c"]`.
Usando a notação de colchetes, agora nos redefinimos o item no índice 1, alterando a string `b`, para `not b anymore`. Agora `ourArray` é `["a", "not b anymore", "c"]`.
# --instructions--
In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides the letter `b`.
A fim de concluir esse desafio, defina a segunda posição (index `1`) do `myArray` como qualquer coisa que deseja, exceto a letra `b`.
# --hints--
`myArray[0]` should be equal to the letter `a`
`myArray[0]` deve ser igual à letra `a`
```js
assert.strictEqual(myArray[0], 'a');
```
`myArray[1]` should not be equal to the letter `b`
`myArray[1]` não deve ser igual à letra `b`
```js
assert.notStrictEqual(myArray[1], 'b');
```
`myArray[2]` should be equal to the letter `c`
`myArray[2]` deve ser igual à letra `c`
```js
assert.strictEqual(myArray[2], 'c');
```
`myArray[3]` should be equal to the letter `d`
`myArray[3]` deve ser igual à letra `d`
```js
assert.strictEqual(myArray[3], 'd');

View File

@ -1,6 +1,6 @@
---
id: 587d7b7c367417b2b2512b1a
title: Access Property Names with Bracket Notation
title: Acesse Nomes de Propriedades com Notação de Colchetes
challengeType: 1
forumTopicId: 301150
dashedName: access-property-names-with-bracket-notation
@ -8,28 +8,28 @@ dashedName: access-property-names-with-bracket-notation
# --description--
In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that our `foods` object is being used in a program for a supermarket cash register. We have some function that sets the `selectedFood` and we want to check our `foods` object for the presence of that food. This might look like:
No primeiro desafio, nós mencionamos o uso da notação de colchetes como uma forma de acessar valores das propriedades usando a avaliação de uma variável. Por exemplo, imagine que nosso objeto `foods` está sendo usado em um programa para a caixa-registradora de um supermercado. Nós temos algumas funções que definem `selectedFood` e nós queremos checar a presença da `selectedFood` em nosso objeto `foods`. Isso pode parecer assim:
```js
let selectedFood = getCurrentFood(scannedItem);
let inventory = foods[selectedFood];
```
This code will evaluate the value stored in the `selectedFood` variable and return the value of that key in the `foods` object, or `undefined` if it is not present. Bracket notation is very useful because sometimes object properties are not known before runtime or we need to access them in a more dynamic way.
Esse código irá avaliar o valor armazenado na variável `selectedFood` e retorna o valor daquela chave no objeto `foods`, ou `undefined` se não estiver presente. Notação de colchetes é muito útil porque às vezes as propriedades de um objeto não são conhecidas antes da execução ou nós precisamos acessá-las de uma forma mais dinâmica.
# --instructions--
We've defined a function, `checkInventory`, which receives a scanned item as an argument. Return the current value of the `scannedItem` key in the `foods` object. You can assume that only valid keys will be provided as an argument to `checkInventory`.
Nós definimos uma função, `checkInventory`, a qual recebe um item escaneado como argumento. Retornar o valor atual da chave `scannedItem` no objeto `foods`. Você pode assumir que apenas chaves válidas serão fornecidas como um argumento para `checkInventory`.
# --hints--
`checkInventory` should be a function.
`checkInventory` deve ser uma função.
```js
assert.strictEqual(typeof checkInventory, 'function');
```
The `foods` object should have only the following key-value pairs: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
O objeto `foods` deve ter apenas as duplas de chaves e valores a seguir: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
```js
assert.deepEqual(foods, {
@ -42,19 +42,19 @@ assert.deepEqual(foods, {
});
```
`checkInventory("apples")` should return `25`.
`checkInventory("apples")` deve retornar `25`.
```js
assert.strictEqual(checkInventory('apples'), 25);
```
`checkInventory("bananas")` should return `13`.
`checkInventory("bananas")` deve retornar `13`.
```js
assert.strictEqual(checkInventory('bananas'), 13);
```
`checkInventory("strawberries")` should return `27`.
`checkInventory("strawberries")` deve retornar `27`.
```js
assert.strictEqual(checkInventory('strawberries'), 27);

View File

@ -1,6 +1,6 @@
---
id: 587d78b2367417b2b2512b0e
title: Add Items to an Array with push() and unshift()
title: Adicione itens em um Array com push() e unshift()
challengeType: 1
forumTopicId: 301151
dashedName: add-items-to-an-array-with-push-and-unshift
@ -8,9 +8,9 @@ dashedName: add-items-to-an-array-with-push-and-unshift
# --description--
An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are <dfn>mutable</dfn>. In this challenge, we will look at two methods with which we can programmatically modify an array: `Array.push()` and `Array.unshift()`.
O comprimento de um array, como os tipos de dados que pode conter, não são fixos. Arrays podem ser definidos com um comprimento de qualquer número de elementos e elementos podem ser adicionados e removidos ao decorrer do tempo; em outras palavras, arrays são <dfn>mutáveis</dfn>. Nesse desafio, nós olharemos dois métodos com os quais podemos modificar programaticamente um array: `Array.push()` e `Array.unshift()`.
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the `push()` method adds elements to the end of an array, and `unshift()` adds elements to the beginning. Consider the following:
Ambos os métodos recebem 1 ou mais elementos como parâmetros e adiciona esses elementos ao array no qual o método está sendo chamado; o método `push()` adiciona elementos ao final do array, e `unshift()` adiciona no início. Considere o seguinte:
```js
let twentyThree = 'XXIII';
@ -19,21 +19,21 @@ let romanNumerals = ['XXI', 'XXII'];
romanNumerals.unshift('XIX', 'XX');
```
`romanNumerals` would have the value `['XIX', 'XX', 'XXI', 'XXII']`.
`romanNumerals` teria os valores `['XIX', 'XX', 'XXI', 'XXII']`.
```js
romanNumerals.push(twentyThree);
```
`romanNumerals` would have the value `['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`. Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.
`romanNumerals` teria os valores `['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`. Note que nós também podemos passar variáveis, as quais nos permitem uma flexibilidade ainda maior na modificação dinâmica dos dados de nosso array.
# --instructions--
We have defined a function, `mixedNumbers`, which we are passing an array as an argument. Modify the function by using `push()` and `unshift()` to add `'I', 2, 'three'` to the beginning of the array and `7, 'VIII', 9` to the end so that the returned array contains representations of the numbers 1-9 in order.
Nos definimos uma função, `mixedNumbers`, na qual estamos passando o array como um argumento. Modifique a função usando `push()` e `unshift()` para adicionar `'1', 2, 'three'` no início do array e `7, 'VIII', 9` ao final para que o array retornado contenha a representação dos números de 1 a 9 em ordem.
# --hints--
`mixedNumbers(["IV", 5, "six"])` should now return `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
`mixedNumbers(["IV", 5, "six"])` agora deve retornar `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
```js
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
@ -49,13 +49,13 @@ assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
]);
```
The `mixedNumbers` function should utilize the `push()` method
A função `mixedNumbers` deve usar o método `push()`
```js
assert(mixedNumbers.toString().match(/\.push/));
```
The `mixedNumbers` function should utilize the `unshift()` method
A função `mixedNumbers` deve usar o método `unshift()`
```js
assert(mixedNumbers.toString().match(/\.unshift/));

View File

@ -1,6 +1,6 @@
---
id: 587d78b3367417b2b2512b11
title: Add Items Using splice()
title: Adicione Itens Usando splice()
challengeType: 1
forumTopicId: 301152
dashedName: add-items-using-splice
@ -8,7 +8,7 @@ dashedName: add-items-using-splice
# --description--
Remember in the last challenge we mentioned that `splice()` can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
Se lembra que no último desafio mencionamos que `splice()` pode receber até três parâmetros? Bem, você pode usar o terceiro parâmetro, composto por um ou mais elementos, para adicioná-los ao array. Isso pode ser incrivelmente útil para mudar rapidamente um elemento, ou um conjunto de elementos, para outro.
```js
const numbers = [10, 11, 12, 12, 15];
@ -19,17 +19,17 @@ numbers.splice(startIndex, amountToDelete, 13, 14);
console.log(numbers);
```
The second occurrence of `12` is removed, and we add `13` and `14` at the same index. The `numbers` array would now be `[ 10, 11, 12, 13, 14, 15 ]`.
A segunda ocorrência de `12` é removida, e adicionamos `13` e `14` no mesmo índice. O array `numbers` agora seria `[ 10, 11, 12, 13, 14, 15 ]`.
Here, we begin with an array of numbers. Then, we pass the following to `splice()`: The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note that there can be any number of elements (separated by commas) following `amountToDelete`, each of which gets inserted.
Aqui, começamos com um array de números. Em seguida, passamos o seguinte para `splice()`: O índice no qual começar a deletar os elementos (3), o número de elementos a serem deletados (1) e os argumentos restantes (13, 14) serão inseridos com início no mesmo índice. Note que três pode ser qualquer número de elementos (separado por vírgulas) seguindo `amountToDelete`, cada um dos quais são inseridos.
# --instructions--
We have defined a function, `htmlColorNames`, which takes an array of HTML colors as an argument. Modify the function using `splice()` to remove the first two elements of the array and add `'DarkSalmon'` and `'BlanchedAlmond'` in their respective places.
Definimos uma função, `htmlColorNames`, a qual recebe um array de cores HTML como argumento. Modifique a função usando `splice()` para remover os dois primeiros elementos do array e adicionar `'DarkSalmon'` e `'BlanchedAlmond'` em seus respectivos lugares.
# --hints--
`htmlColorNames` should return `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
`htmlColorNames` deve retornar `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
```js
assert.deepEqual(
@ -50,19 +50,19 @@ assert.deepEqual(
);
```
The `htmlColorNames` function should utilize the `splice()` method
A função `htmlColorNames` deve utilizar o método `splice()`
```js
assert(/.splice/.test(code));
```
You should not use `shift()` or `unshift()`.
Você não deve usar `shift()` ou `unshift()`.
```js
assert(!/shift|unshift/.test(code));
```
You should not use array bracket notation.
Você não deve usar a notação de colchetes de array.
```js
assert(!/\[\d\]\s*=/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 587d7b7c367417b2b2512b18
title: Add Key-Value Pairs to JavaScript Objects
title: Adicione Pares de Chave-Valor a objetos JavaScript
challengeType: 1
forumTopicId: 301153
dashedName: add-key-value-pairs-to-javascript-objects
@ -8,7 +8,7 @@ dashedName: add-key-value-pairs-to-javascript-objects
# --description--
At their most basic, objects are just collections of <dfn>key-value</dfn> pairs. In other words, they are pieces of data (<dfn>values</dfn>) mapped to unique identifiers called <dfn>properties</dfn> (<dfn>keys</dfn>). Take a look at an example:
Em suas formas mais básicas, objetos são apenas coleções de pares de <dfn>chave-valor</dfn>. Em outras palavras, eles são pedaços de dados (<dfn>valores</dfn>) mapeados para identificadores únicos chamados <dfn>propriedades</dfn> (<dfn>chaves</dfn>). Dê uma olhada no exemplo:
```js
const tekkenCharacter = {
@ -18,19 +18,19 @@ const tekkenCharacter = {
};
```
The above code defines a Tekken video game character object called `tekkenCharacter`. It has three properties, each of which map to a specific value. If you want to add an additional property, such as "origin", it can be done by assigning `origin` to the object:
O código acima define um objeto de caractere de jogo Tekken chamado `tekkenCharacter`. Tem três propriedades, em que cada uma é mapeada para um valor específico. Se você quer adicionar uma propriedade adicional, como "origin", pode ser feito ao atribuir `origin` ao objeto:
```js
tekkenCharacter.origin = 'South Korea';
```
This uses dot notation. If you were to observe the `tekkenCharacter` object, it will now include the `origin` property. Hwoarang also had distinct orange hair. You can add this property with bracket notation by doing:
Isso usa notação de ponto. Se você observar o objeto `tekkenCharacter`, agora incluirá a propriedade `origin`. Hwoarang também tinha distintos cabelos laranja. Você pode adicionar essa propriedade com notação de colchetes fazendo:
```js
tekkenCharacter['hair color'] = 'dyed orange';
```
Bracket notation is required if your property has a space in it or if you want to use a variable to name the property. In the above case, the property is enclosed in quotes to denote it as a string and will be added exactly as shown. Without quotes, it will be evaluated as a variable and the name of the property will be whatever value the variable is. Here's an example with a variable:
A notação de colchete é necessária se sua propriedade tem um espaço nele ou se você deseja usar uma variável para nomear a propriedade. No caso acima, a propriedade está entre aspas para denotá-la como uma string e será adicionada exatamente como mostrada. Sem aspas, ele será avaliado como uma variável e o nome da propriedade será qualquer valor que a variável seja. Aqui está um exemplo com uma variável:
```js
const eyes = 'eye color';
@ -38,7 +38,7 @@ const eyes = 'eye color';
tekkenCharacter[eyes] = 'brown';
```
After adding all the examples, the object will look like this:
Após adicionar todos os exemplos, o objeto ficará assim:
```js
{
@ -53,35 +53,35 @@ After adding all the examples, the object will look like this:
# --instructions--
A `foods` object has been created with three entries. Using the syntax of your choice, add three more entries to it: `bananas` with a value of `13`, `grapes` with a value of `35`, and `strawberries` with a value of `27`.
O objeto `foods` foi criado com três entradas. Usando a sintaxe de sua escolha, adicione mais três entradas a ele: `bananas` com um valor de `13`, `uvas` com um valor de `35` e `morangos` com um valor de `27`.
# --hints--
`foods` should be an object.
`foods` deve ser um objeto.
```js
assert(typeof foods === 'object');
```
The `foods` object should have a key `bananas` with a value of `13`.
O objeto `foods` deve ter a chave `bananas` com o valor de `13`.
```js
assert(foods.bananas === 13);
```
The `foods` object should have a key `grapes` with a value of `35`.
O objeto `foods` deve ter a chave `grapes` com o valor de `35`.
```js
assert(foods.grapes === 35);
```
The `foods` object should have a key `strawberries` with a value of `27`.
O objeto `foods` deve ter a chave `strawberries` com o valor de `35`.
```js
assert(foods.strawberries === 27);
```
The key-value pairs should be set using dot or bracket notation.
Os pares de chave-valor devem serem definidos usando a notação de ponto ou de colchetes.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b14
title: Check For The Presence of an Element With indexOf()
title: Verifique a Presença de um Elemento com indexOf()
challengeType: 1
forumTopicId: 301154
dashedName: check-for-the-presence-of-an-element-with-indexof
@ -8,9 +8,9 @@ dashedName: check-for-the-presence-of-an-element-with-indexof
# --description--
Since arrays can be changed, or *mutated*, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, `indexOf()`, that allows us to quickly and easily check for the presence of an element on an array. `indexOf()` takes an element as a parameter, and when called, it returns the position, or index, of that element, or `-1` if the element does not exist on the array.
Já que arrays podem ser alterados, ou *mutadas*, a qualquer momentos, não garantia de onde um pedaço de dado estará em um determinado array, ou se esse elemento se quer existe. Felizmente, JavaScript nos fornece com outro método embutido, `indexOf()`, que nos permite rapidamente e facilmente checar pela presença de um elemento em um array. `indexOf()` recebe um elemento como parâmetro, e quando chamado, retorna a posição, ou índice, daquele elemento, ou `-1` se o elemento não existe no array.
For example:
Por exemplo:
```js
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
@ -20,21 +20,21 @@ fruits.indexOf('oranges');
fruits.indexOf('pears');
```
`indexOf('dates')` returns `-1`, `indexOf('oranges')` returns `2`, and `indexOf('pears')` returns `1` (the first index at which each element exists).
`indexOf('dates')` retorna `-1`, `indexOf('oranges')` retorna `2` e `indexOf('pears')` retorna `1` (o primeiro índice no qual cada elemento existe).
# --instructions--
`indexOf()` can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, `quickCheck`, that takes an array and an element as arguments. Modify the function using `indexOf()` so that it returns `true` if the passed element exists on the array, and `false` if it does not.
`indexOf()` pode ser incrivelmente útil para verificar rapidamente a presença de um elemento em um array. Definimos uma função, `quickCheck`, que recebe um array e um elemento como argumentos. Modifique a função usando `indexOf()` para que retorne `true` se o elemento passado existe no array, e`false` caso não exista.
# --hints--
The `quickCheck` function should return a boolean (`true` or `false`), not a string (`"true"` or `"false"`)
A função `quickCheck` deve retornar um booleano (`true` ou `false`), e não uma string (`"true"` ou `"false"`)
```js
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
```
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` should return `false`
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` deve retornar `false`
```js
assert.strictEqual(
@ -43,7 +43,7 @@ assert.strictEqual(
);
```
`quickCheck(["onions", "squash", "shallots"], "onions")` should return `true`
`quickCheck(["onions", "squash", "shallots"], "onions")` deve retornar `true`
```js
assert.strictEqual(
@ -52,19 +52,19 @@ assert.strictEqual(
);
```
`quickCheck([3, 5, 9, 125, 45, 2], 125)` should return `true`
`quickCheck([3, 5, 9, 125, 45, 2], 125)` deve retornar `true`
```js
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
```
`quickCheck([true, false, false], undefined)` should return `false`
`quickCheck([true, false, false], undefined)` deve retornar `false`
```js
assert.strictEqual(quickCheck([true, false, false], undefined), false);
```
The `quickCheck` function should utilize the `indexOf()` method
A função `quickCheck` deve utilizar o método `indexOf()`
```js
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7d367417b2b2512b1c
title: Check if an Object has a Property
title: Verifique se um Objeto tem uma Propriedade
challengeType: 1
forumTopicId: 301155
dashedName: check-if-an-object-has-a-property
@ -8,22 +8,22 @@ dashedName: check-if-an-object-has-a-property
# --description--
Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the `hasOwnProperty()` method and the other uses the `in` keyword. If we have an object `users` with a property of `Alan`, we could check for its presence in either of the following ways:
Agora podemos adicionar, modificar e remover as chaves dos objetos. Mas e se apenas quiséssemos saber se um objeto tem uma propriedade específica? O JavaScript nos fornece duas maneiras diferentes de fazer isso. Um usa o método `hasOwnProperty()` e o outro usa a palavra-chave `in`. Se tivermos um objeto `usuários` com uma propriedade de `Alan`, poderíamos verificar a sua presença de qualquer uma das seguintes maneiras:
```js
users.hasOwnProperty('Alan');
'Alan' in users;
```
Both of these would return `true`.
Ambos esses retornariam `true`.
# --instructions--
Finish writing the function so that it returns true if the object passed to it contains all four names, `Alan`, `Jeff`, `Sarah` and `Ryan` and returns false otherwise.
Termine de escrever a função para que ela retorne verdadeiro se o objeto passado a ela contiver todos os quatro nomes, `Alan`, `Jeff`, `Sarah` e `Ryan` e retorna falso caso contrário.
# --hints--
The `users` object should not be accessed directly
O objeto `users` não deve ser acessado diretamente
```js
@ -31,7 +31,7 @@ assert(code.match(/users/gm).length <= 2)
```
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
O objeto `users` deve conter apenas as chaves `Alan`, `Jeff`, `Sarah` e `Ryan`
```js
assert(
@ -43,13 +43,13 @@ assert(
);
```
The function `isEveryoneHere` should return `true` if `Alan`, `Jeff`, `Sarah`, and `Ryan` are properties on the object passed to it.
A função `isEveryoneHere` deve retornar `true` se `Alan`, `Jeff`, `Sarah`, e `Ryan` forem propriedades do objeto passado como argumento.
```js
assert(isEveryoneHere(users) === true);
```
The function `isEveryoneHere` should return `false` if `Alan` is not a property on the object passed to it.
A função `isEveryoneHere` deve retornar `false` se `Alan` não for uma propriedade do objeto passado como argumento.
```js
assert(
@ -60,7 +60,7 @@ assert(
);
```
The function `isEveryoneHere` should return `false` if `Jeff` is not a property on the object passed to it.
A função `isEveryoneHere` deve retornar `false` se `Jeff` não for uma propriedade no objeto passado como argumento.
```js
assert(
@ -71,7 +71,7 @@ assert(
);
```
The function `isEveryoneHere` should return `false` if `Sarah` is not a property on the object passed to it.
A função `isEveryoneHere` deve retornar `false` se `Sarah` não for uma propriedade do objeto passado como argumento.
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
The function `isEveryoneHere` should return `false` if `Ryan` is not a property on the object passed to it.
A função `isEveryoneHere` deve retornar `false` se `Ryan` não for uma propriedade do objeto passado como argumento.
```js
assert(
@ -119,7 +119,7 @@ let users = {
function isEveryoneHere(userObj) {
// Only change code below this line
// Only change code above this line
}

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b17
title: Combine Arrays with the Spread Operator
title: Combinar Arrays com o Operador Spread
challengeType: 1
forumTopicId: 301156
dashedName: combine-arrays-with-the-spread-operator
@ -8,7 +8,7 @@ dashedName: combine-arrays-with-the-spread-operator
# --description--
Another huge advantage of the <dfn>spread</dfn> operator is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:
Outra grande vantagem do operador <dfn>spread</dfn> é a capacidade de combinar arrays, ou para inserir todos os elementos de um array em outro, em qualquer índice. Com sintaxe mais tradicional, podemos concatenar arrays, mas isso só nos permite combinar arrays no final de um e no início de outro. A sintaxe do spread torna a seguinte operação extremamente simples:
```js
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
@ -16,23 +16,23 @@ let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
```
`thatArray` would have the value `['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']`.
`thatArray` teria o valor `['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']`.
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
Usando a sintaxe de spread, acabamos de conseguir uma operação que teria sido mais complexa e mais verbosa se tivéssemos utilizado métodos tradicionais.
# --instructions--
We have defined a function `spreadOut` that returns the variable `sentence`. Modify the function using the <dfn>spread</dfn> operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`.
Definimos uma função `spreadOut` que retorna a variável `sentença`. Modifique a função usando o operador <dfn>spread</dfn> para que ele retorne o array `['learning', 'to', 'code', 'is', 'fun']`.
# --hints--
`spreadOut` should return `["learning", "to", "code", "is", "fun"]`
`spreadOut` deve retornar `["learning", "to", "code", "is", "fun"]`
```js
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
```
The `spreadOut` function should utilize spread syntax
A função `spreadOut` deve utilizar a sintaxe spread
```js
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b13
title: Copy an Array with the Spread Operator
title: Copiar um Array com o Operador Spread
challengeType: 1
forumTopicId: 301157
dashedName: copy-an-array-with-the-spread-operator
@ -8,24 +8,24 @@ dashedName: copy-an-array-with-the-spread-operator
# --description--
While `slice()` allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy *all* of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: `...`
Enquanto `slice()` nos permite ser seletivo sobre quais elementos de um array copiar, entre várias outras tarefas úteis, o novo operador <dfn>do spread</dfn> da ES6 nos permite facilmente copiar *todos* os elementos de um array, em ordem, com uma sintaxe simples e altamente legível. A sintaxe de spread simplesmente se parece com isso: `...`
In practice, we can use the spread operator to copy an array like so:
Na prática, podemos usar o operador "spread" para copiar um array assim:
```js
let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];
```
`thatArray` equals `[true, true, undefined, false, null]`. `thisArray` remains unchanged and `thatArray` contains the same elements as `thisArray`.
`thatArray` é igual a `[true, true, undefined, false, null]`. `thisArray` permanece inalterado e `thatArray` contém os mesmos elementos que `thisArray`.
# --instructions--
We have defined a function, `copyMachine` which takes `arr` (an array) and `num` (a number) as arguments. The function is supposed to return a new array made up of `num` copies of `arr`. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
Definimos uma função, `copyMachine` que recebe `arr` (um array) e `num` (um número) como argumentos. A função deve retornar um novo array composto de `num` cópias de `arr`. Fizemos a maior parte do trabalho para você, mas ainda não funciona muito bem. Modifique a função usando a sintaxe spread para que ela funcione corretamente (dica: outro método já mencionado pode ser útil aqui!).
# --hints--
`copyMachine([true, false, true], 2)` should return `[[true, false, true], [true, false, true]]`
`copyMachine([true, false, true], 2)` deve retornar `[[true, false, true], [true, false, true]]`
```js
assert.deepEqual(copyMachine([true, false, true], 2), [
@ -34,7 +34,7 @@ assert.deepEqual(copyMachine([true, false, true], 2), [
]);
```
`copyMachine([1, 2, 3], 5)` should return `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
`copyMachine([1, 2, 3], 5)` deve retornar `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
```js
assert.deepEqual(copyMachine([1, 2, 3], 5), [
@ -46,13 +46,13 @@ assert.deepEqual(copyMachine([1, 2, 3], 5), [
]);
```
`copyMachine([true, true, null], 1)` should return `[[true, true, null]]`
`copyMachine([true, true, null], 1)` deve retornar `[[true, true, null]]`
```js
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
```
`copyMachine(["it works"], 3)` should return `[["it works"], ["it works"], ["it works"]]`
`copyMachine(["it works"], 3)` deve retornar `[["it works"], ["it works"], ["it works"]]`
```js
assert.deepEqual(copyMachine(['it works'], 3), [
@ -62,7 +62,7 @@ assert.deepEqual(copyMachine(['it works'], 3), [
]);
```
The `copyMachine` function should utilize the `spread operator` with array `arr`
A função `copyMachine` deve utilizar o operador `spread` com array `arr`
```js
assert(code.match(/\.\.\.arr/));

View File

@ -1,6 +1,6 @@
---
id: 587d7b7a367417b2b2512b12
title: Copy Array Items Using slice()
title: Copiar Itens de um Array Usando slice()
challengeType: 1
forumTopicId: 301158
dashedName: copy-array-items-using-slice
@ -8,7 +8,7 @@ dashedName: copy-array-items-using-slice
# --description--
The next method we will cover is `slice()`. Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters — the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
O próximo método que abordaremos é `slice()`. Em vez de modificar um array, `slice()` copia ou *extrai* um determinado número de elementos para um novo array, deixando o array em que o método é chamado inalterado. `slice()` recebe apenas 2 parâmetros — o primeiro é o índice aonde começar a extração e o segundo é o índice no qual parar a extração (extração ocorrerá até, mas não incluso, esse índice). Considere isto:
```js
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
@ -16,17 +16,17 @@ let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3);
```
`todaysWeather` would have the value `['snow', 'sleet']`, while `weatherConditions` would still have `['rain', 'snow', 'sleet', 'hail', 'clear']`.
`todaysWeather` teria o valor `['snow', 'sleet']`, enquanto `weatherConditions` ainda teria `['rain', 'snow', 'sleet', 'hail', 'clear']`.
In effect, we have created a new array by extracting elements from an existing array.
Assim, criamos um novo array extraindo elementos de um array existente.
# --instructions--
We have defined a function, `forecast`, that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the string elements `warm` and `sunny`.
Definimos uma função, `forecast`, que recebe um array como argumento. Modifique a função usando `slice()` para extrair a informação do array passado como argumento e retorne um novo array contendo os elementos strings `warm` e `sunny`.
# --hints--
`forecast` should return `["warm", "sunny"]`
`forecast` deve retornar `["warm", "sunny"]`
```js
assert.deepEqual(
@ -35,7 +35,7 @@ assert.deepEqual(
);
```
The `forecast` function should utilize the `slice()` method
A função `forecast` deve usar o método `slice()`
```js
assert(/\.slice\(/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b16
title: Create complex multi-dimensional arrays
title: Crie array complexo multidimensional
challengeType: 1
forumTopicId: 301159
dashedName: create-complex-multi-dimensional-arrays
@ -8,9 +8,9 @@ dashedName: create-complex-multi-dimensional-arrays
# --description--
Awesome! You have just learned a ton about arrays! This has been a fairly high level overview, and there is plenty more to learn about working with arrays, much of which you will see in later sections. But before moving on to looking at <dfn>Objects</dfn>, lets take one more look, and see how arrays can become a bit more complex than what we have seen in previous challenges.
Excelente! Você acabou de aprender uma tonelada sobre arrays! Esta foi uma visão geral de nível bastante elevado, e há muito mais para aprender a trabalhar com arrays, muitas das quais você verá em sessões posteriores. Mas antes de passar para a visão de <dfn>objetos</dfn>, vamos dar mais uma olhada e ver como é que as matrizes podem tornar-se um pouco mais complexas do que aquilo que vimos em desafios anteriores.
One of the most powerful features when thinking of arrays as data structures, is that arrays can contain, or even be completely made up of other arrays. We have seen arrays that contain arrays in previous challenges, but fairly simple ones. However, arrays can contain an infinite depth of arrays that can contain other arrays, each with their own arbitrary levels of depth, and so on. In this way, an array can very quickly become very complex data structure, known as a <dfn>multi-dimensional</dfn>, or nested array. Consider the following example:
Uma das características mais poderosas ao pensar em arrays como estruturas de dados, é que arrays podem conter, ou mesmo ser completamente compostas por outros arrays. Vimos arrays que contêm arrays em desafios anteriores, mas que são bastante simples. No entanto, os arrays podem conter uma profundidade infinita de matrizes que podem conter outras matrizes, cada uma com seus próprios níveis arbitrários de profundidade, e assim por diante. Desta forma, um array pode muito rapidamente se tornar uma estrutura de dados muito complexa, conhecida como <dfn>array multi-dimensional</dfn>ou array aninhado. Considere o seguinte exemplo:
```js
let nestedArray = [
@ -31,15 +31,15 @@ let nestedArray = [
];
```
The `deep` array is nested 2 levels deep. The `deeper` arrays are 3 levels deep. The `deepest` arrays are 4 levels, and the `deepest-est?` is 5.
O array `deep` está aninhado com 2 veis de profundidade. Os arrays `mais profundos` são de 3 veis de profundidade. Os `arrays` mais profundos são de 4º níveis, e o ainda `mais profundos` é de 5º nível.
While this example may seem convoluted, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data. However, we can still very easily access the deepest levels of an array this complex with bracket notation:
Embora este exemplo possa parecer complicado, este nível de complexidade não é inédito, ou ainda fora do normal, quando tratando com grandes quantidades de dados. Entretanto, nós ainda podemos facilmente acessar os níveis mais profundos de um array complexo com a notação de colchetes:
```js
console.log(nestedArray[2][1][0][0][0]);
```
This logs the string `deepest-est?`. And now that we know where that piece of data is, we can reset it if we need to:
Isso exibe no console a string `deepest-est?`. Agora que sabemos aonde esse pedaço de dado está, nós podemos redefini-lo se precisarmos:
```js
nestedArray[2][1][0][0][0] = 'deeper still';
@ -47,15 +47,15 @@ nestedArray[2][1][0][0][0] = 'deeper still';
console.log(nestedArray[2][1][0][0][0]);
```
Now it logs `deeper still`.
Agora ele mostra no console `deeper still`.
# --instructions--
We have defined a variable, `myNestedArray`, set equal to an array. Modify `myNestedArray`, using any combination of <dfn>strings</dfn>, <dfn>numbers</dfn>, and <dfn>booleans</dfn> for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string `deep`, on the fourth level, include the string `deeper`, and on the fifth level, include the string `deepest`.
Definimos uma variável, `myNestedArray`, definida igual a um array. Modifique `myNestedArray`, usando qualquer combinação de <dfn>strings</dfn>, <dfn>numbers</dfn>, e <dfn>booleans</dfn> para elementos, para que tenha 5 níveis de profundidade (lembre-se, o array mais extremo é de nível 1). Em algum lugar no terceiro nível, inclua a string `deep`, no quarto nível, inclua a string `deeper`, e no quinto nível, inclua a string `deepest`.
# --hints--
`myNestedArray` should contain only numbers, booleans, and strings as data elements
`myNestedArray` deve conter apenas números, booleans e strings como elementos
```js
assert.strictEqual(
@ -79,7 +79,7 @@ assert.strictEqual(
);
```
`myNestedArray` should have exactly 5 levels of depth
`myNestedArray` deve ter exatamente 5 veis de profundidade
```js
assert.strictEqual(
@ -102,7 +102,7 @@ assert.strictEqual(
);
```
`myNestedArray` should contain exactly one occurrence of the string `deep` on an array nested 3 levels deep
`myNestedArray` deve conter exatamente uma ocorrência da string `deep` no array aninhado de 3 veis de profundidade
```js
assert(
@ -131,7 +131,7 @@ assert(
);
```
`myNestedArray` should contain exactly one occurrence of the string `deeper` on an array nested 4 levels deep
`myNestedArray` deve conter exatamente uma ocorrência da string `deeper` no array aninhado de 4 veis de profundidade
```js
assert(
@ -160,7 +160,7 @@ assert(
);
```
`myNestedArray` should contain exactly one occurrence of the string `deepest` on an array nested 5 levels deep
`myNestedArray` deve conter exatamente uma ocorrência da string `deepest` no array aninhado de 5 veis de profundidade
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7d367417b2b2512b1e
title: Generate an Array of All Object Keys with Object.keys()
title: Gere um Array de Todas as Chaves de Objeto com Object.keys()
challengeType: 1
forumTopicId: 301160
dashedName: generate-an-array-of-all-object-keys-with-object-keys
@ -8,15 +8,15 @@ dashedName: generate-an-array-of-all-object-keys-with-object-keys
# --description--
We can also generate an array which contains all the keys stored in an object using the `Object.keys()` method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.
Também podemos gerar um array o qual contém todas as chaves armazenadas em um objeto usando o método `Object.keys()` e passando um objeto como argumento. Isso retornará um array com strings representando cada propriedade do objeto. Novamente, não terá uma ordem específica para as entradas no array.
# --instructions--
Finish writing the `getArrayOfUsers` function so that it returns an array containing all the properties in the object it receives as an argument.
Termine de escrever a função `getArrayOfUsers` para que retorne um array contendo todas as propriedades do objeto que receber como argumento.
# --hints--
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
O objeto `users` deve conter apenas as chaves `Alan`, `Jeff`, `Sarah` e `Ryan`
```js
assert(
@ -28,7 +28,7 @@ assert(
);
```
The `getArrayOfUsers` function should return an array which contains all the keys in the `users` object
A função `getArrayOfUsers` deve retornar um array o qual contém todas as chaves no objeto `users`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7b367417b2b2512b15
title: Iterate Through All an Array's Items Using For Loops
title: Itere Através de Todos os Itens de um Array Usando Laços For
challengeType: 1
forumTopicId: 301161
dashedName: iterate-through-all-an-arrays-items-using-for-loops
@ -8,9 +8,9 @@ dashedName: iterate-through-all-an-arrays-items-using-for-loops
# --description--
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as `every()`, `forEach()`, `map()`, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple `for` loop.
Às vezes quando trabalhando com arrays, é muito útil ser capaz de iterar sobre cada item para encontrar um ou mais elementos que podemos precisar, ou para manipular o array baseado em qual item atende a determinado critério. JavaScript oferece diversos métodos embutidos que fazem iteração sobre arrays de formas ligeiramente diferentes para alcançar resultados diferentes (como `every()`, `forEach()`, `map()`, etc.). Porém, a técnica mais flexível e que oferece-nos a maior capacidade de controle é o simples laço `for`.
Consider the following:
Considere o seguinte:
```js
function greaterThanTen(arr) {
@ -26,15 +26,15 @@ function greaterThanTen(arr) {
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
```
Using a `for` loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than `10`, and returned a new array, `[12, 14, 80]`, containing those items.
Usando o laço `for`, essa função itera o array e acessa cada elemento do array, e submete-o a um teste simples que nós criamos. Dessa forma, nós determinamos de forma fácil e programática qual item é maior que `10`, e retorna um novo array, `[12, 14, 80]`, contendo esses itens.
# --instructions--
We have defined a function, `filteredArray`, which takes `arr`, a nested array, and `elem` as arguments, and returns a new array. `elem` represents an element that may or may not be present on one or more of the arrays nested within `arr`. Modify the function, using a `for` loop, to return a filtered version of the passed array such that any array nested within `arr` containing `elem` has been removed.
Definimos uma função, `filteredArray`, a qual recebe `arr`, um array aninhado, e `elem` como argumentos, e retornar um novo array. `elem` representa um elemento que pode ou não estar presente em um ou mais dos arrays aninhados dentro de `arr`. Modifique a função, usando o laço `for`, para retornar uma versão filtrada do array recebido tal qual que qualquer array aninhado dentro de `arr` contendo `elem` seja removido.
# --hints--
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[[10, 8, 3], [14, 6, 23]]`
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` deve retornar `[[10, 8, 3], [14, 6, 23]]`
```js
assert.deepEqual(
@ -53,7 +53,7 @@ assert.deepEqual(
);
```
`filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` should return `[["flutes", 4]]`
`filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` deve retornar `[["flutes", 4]]`
```js
assert.deepEqual(
@ -69,7 +69,7 @@ assert.deepEqual(
);
```
`filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` should return `[["amy", "beth", "sam"]]`
`filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` deve retornar `[["amy", "beth", "sam"]]`
```js
assert.deepEqual(
@ -84,7 +84,7 @@ assert.deepEqual(
);
```
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[]`
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` deve retornar `[]`
```js
assert.deepEqual(
@ -101,7 +101,7 @@ assert.deepEqual(
);
```
The `filteredArray` function should utilize a `for` loop
A função `filteredArray` deve usar o laço `for`
```js
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7d367417b2b2512b1d
title: Iterate Through the Keys of an Object with a for...in Statement
title: Itere Através das Chaves de um Objeto com a declaração for...in
challengeType: 1
forumTopicId: 301162
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
@ -8,7 +8,7 @@ dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
# --description--
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our `users` object, this could look like:
Às vezes você pode precisar iterar através de todas as chaves dentro de um objeto. Isso requer uma sintaxe específica no JavaScript chamada de declaração <dfn>for...in</dfn>. Para nosso objeto `users`, isso pode se parecer como:
```js
for (let user in users) {
@ -16,15 +16,15 @@ for (let user in users) {
}
```
This would log `Alan`, `Jeff`, `Sarah`, and `Ryan` - each value on its own line.
Isso iria exibir no console `Alan`, `Jeff`, `Sarah` e `Ryan` - cada valor em sua própria linha.
In this statement, we defined a variable `user`, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.
Nessa declaração, definimos uma variável `user` e, como você pode ver, essa variável é redefinida durante cada iteração para cada chave do objeto conforme o comando se repete através do objeto, resultando em cada nome de usuário sendo exibido no console.
**NOTE:** Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
**Note:** Objetos não mantém uma ordem para as chaves armazenadas como arrays fazem; Portanto a posição de uma chave em um objeto, ou a ordem relativa na qual ela aparece, é irrelevante quando referenciando ou acessando aquela chave.
# --instructions--
We've defined a function `countOnline` which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose `online` property is set to `true`. An example of a users object which could be passed to `countOnline` is shown below. Each user will have an `online` property with either a `true` or `false` value.
Nós definimos uma função `countOnline` a qual aceita um argumento (um objeto usuário). Use a declaração <dfn>for...in</dfn> dentro dessa função para iterar o objeto users passado para a função, e retorne o número de users o qual possuam a propriedade `online` definida como `true`. Um exemplo de um objeto users o qual pode ser passado para `countOnline` é mostrado abaixo. Cada usuário terá a propriedade `online` com um valor `true` ou `false`.
```js
{
@ -42,7 +42,7 @@ We've defined a function `countOnline` which accepts one argument (a users objec
# --hints--
The function `countOnline` should use a `for in` statement to iterate through the object keys of the object passed to it.
A função `countOnline` deve usar a instrução `for in` para iterar através das chaves de um objeto passado para ele.
```js
assert(
@ -52,19 +52,19 @@ assert(
);
```
The function `countOnline` should return `1` when the object `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` is passed to it
A função `countOnline` deve retornar `1` quando o objeto `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` for passado para ele
```js
assert(countOnline(usersObj1) === 1);
```
The function `countOnline` should return `2` when the object `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` is passed to it
A função `countOnline` deve retornar `2` quando o objeto `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` for passado para ele
```js
assert(countOnline(usersObj2) === 2);
```
The function `countOnline` should return `0` when the object `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` is passed to it
A função `countOnline` deve retornar `0` quando o objeto `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` for passado para ele
```js
assert(countOnline(usersObj3) === 0);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7d367417b2b2512b1f
title: Modify an Array Stored in an Object
title: Modifique o Array Armazenado em um Objeto
challengeType: 1
forumTopicId: 301163
dashedName: modify-an-array-stored-in-an-object
@ -8,21 +8,21 @@ dashedName: modify-an-array-stored-in-an-object
# --description--
Now you've seen all the basic operations for JavaScript objects. You can add, modify, and remove key-value pairs, check if keys exist, and iterate over all the keys in an object. As you continue learning JavaScript you will see even more versatile applications of objects. Additionally, the Data Structures lessons located in the Coding Interview Prep section of the curriculum also cover the ES6 <dfn>Map</dfn> and <dfn>Set</dfn> objects, both of which are similar to ordinary objects but provide some additional features. Now that you've learned the basics of arrays and objects, you're fully prepared to begin tackling more complex problems using JavaScript!
Agora você já viu todas as operações básicas para os objetos JavaScript. Você pode adicionar, modificar e remover pares de chave-valor, verifique se a chave existe e itere sobre todas as chaves em um objeto. Conforme continuar aprendendo JavaScript você verá aplicações de objetos ainda mais versáteis. Adicionalmente, as aulas de Estrutura de Dados localizadas na seção Preparação para Entrevista de Codificação do curriculum também cobrem os objetos ES6 <dfn>Map</dfn> e <dfn>Set</dfn>, ambos são semelhantes a objetos comuns, mas fornecem alguns recursos adicionais. Agora que você aprendeu o básico de arrays e objetos, você está totalmente preparado para começar a resolver problemas mais complexos usando JavaScript!
# --instructions--
Take a look at the object we've provided in the code editor. The `user` object contains three keys. The `data` key contains five keys, one of which contains an array of `friends`. From this, you can see how flexible objects are as data structures. We've started writing a function `addFriend`. Finish writing it so that it takes a `user` object and adds the name of the `friend` argument to the array stored in `user.data.friends` and returns that array.
Dê uma olhada no objeto que fornecemos no editor de código. O objeto `user` contém três chaves. A chave `data` contém 5 chaves, uma delas possui um array de `friends`. A partir disso, você pode ver como objetos são flexíveis assim como estruturas de dados. Nós começamos escrevendo a função `addFriend`. Termine de escrevê-la para que receba um objeto `user` e adicione o nome do argumento `friend` no array armazenado em `user.data.friends` e retorne esse array.
# --hints--
The `user` object should have `name`, `age`, and `data` keys.
O objeto `user` deve ter as chaves `name`, `age` e `data`.
```js
assert('name' in user && 'age' in user && 'data' in user);
```
The `addFriend` function should accept a `user` object and a `friend` string as arguments and add the friend to the array of `friends` in the `user` object.
A função `addFriend` deve aceitar o objeto `user` e a string `friend` como argumentos e adicionar friend ao array `friends` no objeto `user`.
```js
assert(
@ -35,7 +35,7 @@ assert(
);
```
`addFriend(user, "Pete")` should return `["Sam", "Kira", "Tomo", "Pete"]`.
`addFriend(user, "Pete")` deve retornar `["Sam", "Kira", "Tomo", "Pete"]`.
```js
assert.deepEqual(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7c367417b2b2512b19
title: Modify an Object Nested Within an Object
title: Modifique um Objeto Aninhado Dentro de um Objeto
challengeType: 1
forumTopicId: 301164
dashedName: modify-an-object-nested-within-an-object
@ -8,7 +8,7 @@ dashedName: modify-an-object-nested-within-an-object
# --description--
Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects. Consider the following:
Agora vamos dar uma olhada em um objeto ligeiramente mais complexo. Propriedades de objeto podem ser aninhadas para uma profundidade arbitrária e os seus valores podem ser de qualquer tipo de dado suportado pelo JavaScript, incluindo arrays e até mesmo objetos. Considere o seguinte:
```js
let nestedObject = {
@ -26,7 +26,7 @@ let nestedObject = {
};
```
`nestedObject` has three properties: `id` (value is a number), `date` (value is a string), and `data` (value is an object with its nested structure). While structures can quickly become complex, we can still use the same notations to access the information we need. To assign the value `10` to the `busy` property of the nested `onlineStatus` object, we use dot notation to reference the property:
`nestedObject` possui três propriedades: `id` (o valor é um número), `date` (o valor é uma string) e `data`(o valor é um objeto com sua estrutura aninhada). Enquanto estruturas podem se tornar rapidamente complexas, nós ainda podemos usar as mesmas notações para acessar as informações que precisamos. Para atribuir o valor `10` para a propriedade `busy` do objeto aninhado `onlineStatus`, nós usamos a notação de ponto para referenciar a propriedade:
```js
nestedObject.data.onlineStatus.busy = 10;
@ -34,11 +34,11 @@ nestedObject.data.onlineStatus.busy = 10;
# --instructions--
Here we've defined an object `userActivity`, which includes another object nested within it. Set the value of the `online` key to `45`.
Aqui nós definimos um objeto `userActivity`, o qual inclui outro objeto aninhado dentro dele. Defina o valor da chave `online` para `45`.
# --hints--
`userActivity` should have `id`, `date` and `data` properties.
`userActivity` deve ter as propriedades `id`, `date` e `data`.
```js
assert(
@ -46,19 +46,19 @@ assert(
);
```
`userActivity` should have a `data` key set to an object with keys `totalUsers` and `online`.
`userActivity` deve ter uma chave `data` definida para um objeto com as chaves `totalUsers` e `online`.
```js
assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
```
The `online` property nested in the `data` key of `userActivity` should be set to `45`
A propriedade `online` aninhada na chave `data` de `userActivity` deve ser definida para `45`
```js
assert(userActivity.data.online === 45);
```
The `online` property should be set using dot or bracket notation.
A propriedade `online` deve ser definindo usando a notação de ponto ou de colchetes.
```js
assert.strictEqual(code.search(/online: 45/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d78b2367417b2b2512b0f
title: Remove Items from an Array with pop() and shift()
title: Remova Itens de um Array com pop() e shift()
challengeType: 1
forumTopicId: 301165
dashedName: remove-items-from-an-array-with-pop-and-shift
@ -8,9 +8,9 @@ dashedName: remove-items-from-an-array-with-pop-and-shift
# --description--
Both `push()` and `unshift()` have corresponding methods that are nearly functional opposites: `pop()` and `shift()`. As you may have guessed by now, instead of adding, `pop()` *removes* an element from the end of an array, while `shift()` removes an element from the beginning. The key difference between `pop()` and `shift()` and their cousins `push()` and `unshift()`, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
Tanto `push()` e `unshift()` possuem métodos correspondentes que são quase opostos funcionais: `pop()` e `shift()`. Como você já pode ter adivinhado, em vez de adicionar, `pop()` *remove* um elemento do fim de um array, enquanto `shift()` remove um elemento do início. A diferença chave entre `pop()` e `shift()` e seus primos `push()` e `unshift()`, é que nenhum dos métodos recebe parâmetros, e cada um só permite que seja modificado um elemento de cada vez de um array.
Let's take a look:
Vamos dar uma olhada:
```js
let greetings = ['whats up?', 'hello', 'see ya!'];
@ -18,29 +18,29 @@ let greetings = ['whats up?', 'hello', 'see ya!'];
greetings.pop();
```
`greetings` would have the value `['whats up?', 'hello']`.
`greetings` teria o valor `['whats up?', 'hello']`.
```js
greetings.shift();
```
`greetings` would have the value `['hello']`.
`greetings` teria o valor `['hello']`.
We can also return the value of the removed element with either method like this:
Nós também podemos retornar o valor do elemento removido com qualquer método dessa forma:
```js
let popped = greetings.pop();
```
`greetings` would have the value `[]`, and `popped` would have the value `hello`.
`greetings` teria o valor `[]` e `popped` teria o valor `hello`.
# --instructions--
We have defined a function, `popShift`, which takes an array as an argument and returns a new array. Modify the function, using `pop()` and `shift()`, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
Nós definimos uma função, `popShift`, a qual recebe um array como argumento e retorna um novo array. Modifique a função, usando `pop()` e `shift()`, para remover o primeiro e o último elemento do array passado como argumento, e atribua os valores removidos para suas variáveis correspondentes, para que o array retornado contenha seus valores.
# --hints--
`popShift(["challenge", "is", "not", "complete"])` should return `["challenge", "complete"]`
`popShift(["challenge", "is", "not", "complete"])` deve retornar `["challenge", "complete"]`
```js
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
@ -49,13 +49,13 @@ assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
]);
```
The `popShift` function should utilize the `pop()` method
A função `popShift` deve utilizar o método `pop()`
```js
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
```
The `popShift` function should utilize the `shift()` method
A função `popShift` deve utilizar o método `shift()`
```js
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);

View File

@ -1,6 +1,6 @@
---
id: 587d78b2367417b2b2512b10
title: Remove Items Using splice()
title: Remova Itens Usando splice()
challengeType: 1
forumTopicId: 301166
dashedName: remove-items-using-splice
@ -8,9 +8,9 @@ dashedName: remove-items-using-splice
# --description--
Ok, so we've learned how to remove elements from the beginning and end of arrays using `shift()` and `pop()`, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where `splice()` comes in. `splice()` allows us to do just that: **remove any number of consecutive elements** from anywhere in an array.
Ok, então aprendemos como remover elementos do início e do fim de arrays usando `shift()` e `pop()`, mas e se quisermos remover um elemento de algum lugar do meio? Ou remover mais de um elemento de uma vez? Bem, é aí que `splice()` pode ser útil. `splice()` nos permite fazer isso: **remova qualquer número de elementos consecutivos** de qualquer lugar no array.
`splice()` can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of `splice()` are integers which represent indexes, or positions, of the array that `splice()` is being called upon. And remember, arrays are *zero-indexed*, so to indicate the first element of an array, we would use `0`. `splice()`'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
`splice` pode receber 3 parâmetros, mas por agora, nós focaremos apenas nos 2 primeiros. Os dois primeiros parâmetros de `splice()` são inteiros que representam índices, ou posições, do array do qual o método `splice()` está sendo chamado. E lembre-se, arrays são *indexados a zero*, então para indicar o primeiro elemento do array, usaríamos `0`. O primeiro parâmetro de `splice()` representa o índice no array do qual começar a remover elementos, enquanto o segundo parâmetro indica o número de elementos a serem removidos. Por exemplo:
```js
let array = ['today', 'was', 'not', 'so', 'great'];
@ -18,9 +18,9 @@ let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2);
```
Here we remove 2 elements, beginning with the third element (at index 2). `array` would have the value `['today', 'was', 'great']`.
Aqui nós removemos 2 elementos, começando com o terceiro elemento (no índice 2). `array` teria o valor `['today', 'was', 'great']`.
`splice()` not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
`splice()` não apenas modifica o array do qual está sendo chamado, mas também retorna um novo array contendo os valores dos elementos removidos:
```js
let array = ['I', 'am', 'feeling', 'really', 'happy'];
@ -28,15 +28,15 @@ let array = ['I', 'am', 'feeling', 'really', 'happy'];
let newArray = array.splice(3, 2);
```
`newArray` has the value `['really', 'happy']`.
`newArray` tem o valor `['really', 'happy']`.
# --instructions--
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of `10`.
Iniciamos um array `arr`. Use `splice()` para remover elementos do `arr`, para que apenas contenha elementos que somam ao valor de `10`.
# --hints--
You should not change the original line of `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
Você não deve alterar a linha original: `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
```js
assert(
@ -44,7 +44,7 @@ assert(
);
```
`arr` should only contain elements that sum to `10`.
`arr` deve conter apenas elementos que somam a `10`.
```js
assert.strictEqual(
@ -53,13 +53,13 @@ assert.strictEqual(
);
```
Your code should utilize the `splice()` method on `arr`.
Seu código deve utilizar o método `splice()` em `arr`.
```js
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
```
The splice should only remove elements from `arr` and not add any additional elements to `arr`.
O splice deve remover apenas os elementos de `arr` e não adicionar qualquer elemento adicional para `arr`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b7e367417b2b2512b20
title: Use an Array to Store a Collection of Data
title: Use um Array para Armazenar uma Coleção de Dados
challengeType: 1
forumTopicId: 301167
dashedName: use-an-array-to-store-a-collection-of-data
@ -8,16 +8,16 @@ dashedName: use-an-array-to-store-a-collection-of-data
# --description--
The below is an example of the simplest implementation of an array data structure. This is known as a <dfn>one-dimensional array</dfn>, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains <dfn>booleans</dfn>, <dfn>strings</dfn>, and <dfn>numbers</dfn>, among other valid JavaScript data types:
Abaixo está um exemplo da implementação mais simples de uma estrutura de dados array. Isso é conhecido como <dfn>array unidimensional</dfn>, significando que tem apenas 1 nível de profundidade, ou que não possui nenhum outro array aninhado dentro de si. Note que possui <dfn>booleans</dfn>, <dfn>strings</dfn> e <dfn>numbers</dfn>, entre outros tipos de dados do JavaScript válidos:
```js
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
console.log(simpleArray.length);
```
The `console.log` call displays `7`.
A chamada a `console.log` exibe `7`.
All arrays have a length property, which as shown above, can be very easily accessed with the syntax `Array.length`. A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
Todos os arrays possuem uma propriedade length, conforme mostrada acima, pode ser muito facilmente acessado com a sintaxe `Array.length`. Uma implementação mais complexa de um array pode ser vista abaixo. Isso é conhecido como um <dfn>array multidimensional</dfn>, ou um array que contém outros arrays. Note que esse array também contém <dfn>objetos</dfn> JavaScript, os quais examinaremos bem de perto na próxima seção, mas por agora, tudo que você precisa saber é que arrays também são capazes de armazenar objetos complexos.
```js
let complexArray = [
@ -46,35 +46,35 @@ let complexArray = [
# --instructions--
We have defined a variable called `yourArray`. Complete the statement by assigning an array of at least 5 elements in length to the `yourArray` variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
Definimos uma variável chamada `yourArray`. Complete a instrução atribuindo um array de pelo menos 5 elementos de comprimento à variável para a variável `yourArray`. Seu array deve conter pelo menos um <dfn>string</dfn>, um <dfn>number</dfn> e um <dfn>boolean</dfn>.
# --hints--
`yourArray` should be an array.
`yourArray` deve ser um array.
```js
assert.strictEqual(Array.isArray(yourArray), true);
```
`yourArray` should be at least 5 elements long.
`yourArray` deve ter pelo menos 5 elementos.
```js
assert.isAtLeast(yourArray.length, 5);
```
`yourArray` should contain at least one `boolean`.
`yourArray` deve conter pelo menos um `boolean`.
```js
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
```
`yourArray` should contain at least one `number`.
`yourArray` deve conter pelo menos um `number`.
```js
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
```
`yourArray` should contain at least one `string`.
`yourArray` deve conter pelo menos um `string`.
```js
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7c367417b2b2512b1b
title: Use the delete Keyword to Remove Object Properties
title: Use a Palavra-Chave delete para Remover Propriedades de Objetos
challengeType: 1
forumTopicId: 301168
dashedName: use-the-delete-keyword-to-remove-object-properties
@ -8,11 +8,11 @@ dashedName: use-the-delete-keyword-to-remove-object-properties
# --description--
Now you know what objects are and their basic features and advantages. In short, they are key-value stores which provide a flexible, intuitive way to structure data, ***and***, they provide very fast lookup time. Throughout the rest of these challenges, we will describe several common operations you can perform on objects so you can become comfortable applying these useful data structures in your programs.
Agora você sabe o que objetos são, seus recursos básicos e suas vantagens. Resumindo, ele são uma forma de armazenar chave-valor que provê uma forma flexível e intuitiva de estruturar dados, ***e***, eles fornecem um desempenho rápido para acessá-los. Ao longo do resto destes desafios, descreveremos diversas operações que você pode executar em objetos, com a finalidade de torná-lo confortável ao usar essas estruturas de dados úteis em seus programas.
In earlier challenges, we have both added to and modified an object's key-value pairs. Here we will see how we can *remove* a key-value pair from an object.
Nos desafios anteriores, nós adicionamos e modificamos os pares de chave-valor de objetos. Aqui veremos como podemos *remover* uma chave-valor de um obeto.
Let's revisit our `foods` object example one last time. If we wanted to remove the `apples` key, we can remove it by using the `delete` keyword like this:
Vamos revisitar nosso objeto de exemplo `foods` uma última vez. Se quisermos remover a chave `apples`, podemos removê-lo usando a palavra-chave `delete` assim:
```js
delete foods.apples;
@ -20,11 +20,11 @@ delete foods.apples;
# --instructions--
Use the delete keyword to remove the `oranges`, `plums`, and `strawberries` keys from the `foods` object.
Use a palavra-chave delete para remover as chaves `oranges`, `plums` e `strawberries` do objeto `foods`.
# --hints--
The `foods` object should only have three keys: `apples`, `grapes`, and `bananas`.
O objeto `foods` deve ter apenas três chaves: `apples`, `grapes` e `bananas`.
```js
assert(
@ -35,7 +35,7 @@ assert(
);
```
The `oranges`, `plums`, and `strawberries` keys should be removed using `delete`.
As chaves `oranges`, `plums` e `strawberries` devem ser removidos usando `delete`.
```js
assert(