chore(i18n,curriculum): update translations (#44114)

This commit is contained in:
camperbot
2021-11-03 08:22:32 -07:00
committed by GitHub
parent 98fe099ef7
commit 18a239e9a1
29 changed files with 216 additions and 219 deletions

View File

@ -18,7 +18,7 @@ Puoi utilizzare HTML, JavaScript, e CSS per completare questo progetto. CSS è r
**User Story #2:** Dovrei vedere un elemento con un corrispondente `id="title"`che contiene una stringa (cioè un testo) che descrive l'oggetto della pagina di tributo (ad esempio "Dr. Norman Borlaug"). **User Story #2:** Dovrei vedere un elemento con un corrispondente `id="title"`che contiene una stringa (cioè un testo) che descrive l'oggetto della pagina di tributo (ad esempio "Dr. Norman Borlaug").
**User story #3:** Dovrei vedere un elemento `div` con un corrispondente `id="img-div"`. **User story #3:** Dovrei vedere un elemento `figure` oppure un elemento `div` con un corrispondente `id="img-div"`.
**User story #4:** All'interno dell'elemento `img-div`, dovrei vedere un elemento `img` con un corrispondente `id="image"`. **User story #4:** All'interno dell'elemento `img-div`, dovrei vedere un elemento `img` con un corrispondente `id="image"`.

View File

@ -25,7 +25,7 @@ Em ordem, essas expressões seriam iguais à `true`, `false`, `false`, `false` e
# --instructions-- # --instructions--
Adicione o operador de desigualdade `!=` na instrução `if` para que a função retorne a string `Not Equal` quando `val` não for equivalente a `99` Adicione o operador de desigualdade `!=` na instrução `if` para que a função retorne a string `Not Equal` quando `val` não for equivalente a `99`.
# --hints-- # --hints--

View File

@ -26,7 +26,7 @@ No segundo exemplo, `3` é um tipo de `Number` e `'3'` é um tipo `String`.
# --instructions-- # --instructions--
Use o operador de igualdade estrita na instrução `if`, para que a função retorne a string `Equal` quando `val` for estritamente igual a `7` Use o operador de igualdade estrita na instrução `if`, para que a função retorne a string `Equal` quando `val` for estritamente igual a `7`.
# --hints-- # --hints--

View File

@ -22,7 +22,7 @@ Em JavaScript, quando o operador `+` é usado com um valor de `String`, ele é c
Exemplo: Exemplo:
```js ```js
var ourStr = "I come first. " + "I come second."; const ourStr = "I come first. " + "I come second.";
``` ```
A string `I come first. I come second.` seria exibida no console. A string `I come first. I come second.` seria exibida no console.
@ -44,10 +44,10 @@ Você deve usar o operador `+` para criar `myStr`.
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g)); assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
``` ```
`myStr` deve ser criada usando a palavra-chave `var`. `myStr` deve ser criada usando a palavra-chave `const`.
```js ```js
assert(/var\s+myStr/.test(code)); assert(/const\s+myStr/.test(code));
``` ```
Você deve atribuir o resultado à variável `myStr`. Você deve atribuir o resultado à variável `myStr`.
@ -73,11 +73,11 @@ assert(/myStr\s*=/.test(code));
## --seed-contents-- ## --seed-contents--
```js ```js
var myStr; // Change this line const myStr = ""; // Change this line
``` ```
# --solutions-- # --solutions--
```js ```js
var myStr = "This is the start. " + "This is the end."; const myStr = "This is the start. " + "This is the end.";
``` ```

View File

@ -16,13 +16,14 @@ Para decrementar em dois cada iteração, nós precisamos alterar nossa iniciali
Nós começaremos em `i = 10` e vamos iterar enquanto `i > 0`. Nós decrementamos `i` por dois em cada iteração com `i -= 2`. Nós começaremos em `i = 10` e vamos iterar enquanto `i > 0`. Nós decrementamos `i` por dois em cada iteração com `i -= 2`.
```js ```js
var ourArray = []; const ourArray = [];
for (var i = 10; i > 0; i -= 2) {
for (let i = 10; i > 0; i -= 2) {
ourArray.push(i); ourArray.push(i);
} }
``` ```
`ourArray` agora vai conter `[10,8, 6,4,2]`. Vamos mudar nossa inicialização e expressão final para que possamos contar para trás em dois para criar um array de números ímpares decrescentes. `ourArray` agora vai conter `[10, 8, 6, 4, 2]`. Vamos mudar nossa inicialização e expressão final para que possamos contar para trás em dois para criar um array de números ímpares decrescentes.
# --instructions-- # --instructions--
@ -42,7 +43,7 @@ Você deve usar o método de array `push`.
assert(code.match(/myArray.push/)); assert(code.match(/myArray.push/));
``` ```
`myArray` deve ser igual a `[9,7,5,3,1]`. `myArray` deve ser igual a `[9, 7, 5, 3, 1]`.
```js ```js
assert.deepEqual(myArray, [9, 7, 5, 3, 1]); assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
@ -60,16 +61,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js ```js
// Setup // Setup
var myArray = []; const myArray = [];
// Only change code below this line // Only change code below this line
``` ```
# --solutions-- # --solutions--
```js ```js
var myArray = []; const myArray = [];
for (var i = 9; i > 0; i -= 2) { for (let i = 9; i > 0; i -= 2) {
myArray.push(i); myArray.push(i);
} }
``` ```

View File

@ -10,7 +10,7 @@ dashedName: declare-a-read-only-variable-with-the-const-keyword
A palavra-chave `let` não é a única nova forma de declarar variáveis. Na versão ES6, você também pode declarar variáveis usando a palavra-chave `const`. A palavra-chave `let` não é a única nova forma de declarar variáveis. Na versão ES6, você também pode declarar variáveis usando a palavra-chave `const`.
`const` possui todos os recursos maravilhosos que `let` tem, com o bônus adicional que variáveis declaradas usando `const` são somente de leitura. Elas têm um valor constante, o que significa que a variável atribuída com `const` não pode ser atribuída novamente. `const` possui todos os recursos maravilhosos que `let` tem, com o bônus adicional que variáveis declaradas usando `const` são somente de leitura. Elas têm um valor constante, o que significa que a variável atribuída com `const` não pode ser atribuída novamente:
```js ```js
const FAV_PET = "Cats"; const FAV_PET = "Cats";
@ -19,9 +19,11 @@ FAV_PET = "Dogs";
O console vai exibir um erro devido à reatribuição do valor de `FAV_PET`. O console vai exibir um erro devido à reatribuição do valor de `FAV_PET`.
Como você pode ver, tentar reatribuir uma variável declarada com `const` lançará um erro. Você sempre deve nomear variáveis que você não quer reatribuir, usando a palavra-chave `const`. Isso ajuda quando você acidentalmente tenta reatribuir uma variável que deveria ser constante. Uma prática comum ao nomear constantes é colocar todas as letras em maiúsculas, com palavras separadas por sublinhado (underscore). Você sempre deve nomear variáveis que você não quer reatribuir, usando a palavra-chave `const`. Isso ajuda quando você acidentalmente tenta reatribuir uma variável que deveria ser constante.
**Observação:** é comum que os desenvolvedores usem nomes de variáveis maiúsculas para valores imutáveis e minúsculas ou camelCase para valores mutáveis (objetos e arrays). Em um desafio posterior, você verá um exemplo de um nome de variável em minúsculo usado para um array. Uma prática comum ao nomear constantes é colocar todas as letras em maiúsculas, com palavras separadas por sublinhado (underscore).
**Observação:** é comum que os desenvolvedores usem nomes de variáveis maiúsculas para valores imutáveis e minúsculas ou camelCase para valores mutáveis (objetos e arrays). Você aprenderá mais sobre objetos, arrays e valores imutáveis e mutáveis em desafios futuros. Em desafios posteriores, você também verá exemplos de identificadores de variáveis maiúsculas, minúsculas ou em camelCase.
# --instructions-- # --instructions--
@ -35,23 +37,33 @@ Altere o código para que todas as variáveis sejam declaradas usando `let` ou `
(getUserInput) => assert(!getUserInput('index').match(/var/g)); (getUserInput) => assert(!getUserInput('index').match(/var/g));
``` ```
`SENTENCE` deve ser uma variável constante declarada com `const`. Você deve alterar `fCC` para uma string toda em letras maiúsculas.
```js ```js
(getUserInput) => assert(getUserInput('index').match(/(const SENTENCE)/g)); (getUserInput) => {
assert(getUserInput('index').match(/(FCC)/));
assert(!getUserInput('index').match(/fCC/));
}
``` ```
A variável `i` deve ser declarada com `let`. `FCC` deve ser uma variável constante declarada com `const`.
```js ```js
(getUserInput) => assert(getUserInput('index').match(/(let i)/g)); assert.equal(FCC, 'freeCodeCamp');
assert.match(code, /const\s+FCC/);
``` ```
`console.log` deve ser alterado para imprimir a variável `SENTENCE`. A variável `fact` deve ser declarada com `let`.
```js
(getUserInput) => assert(getUserInput('index').match(/(let fact)/g));
```
`console.log` deve ser alterado para imprimir as variáveis `FCC` e `fact`.
```js ```js
(getUserInput) => (getUserInput) =>
assert(getUserInput('index').match(/console\.log\(\s*SENTENCE\s*\)\s*;?/g)); assert(getUserInput('index').match(/console\.log\(\s*FCC\s*\,\s*fact\s*\)\s*;?/g));
``` ```
# --seed-- # --seed--
@ -59,31 +71,18 @@ A variável `i` deve ser declarada com `let`.
## --seed-contents-- ## --seed-contents--
```js ```js
function printManyTimes(str) { var fCC = "freeCodeCamp"; // Change this line
var fact = "is cool!"; // Change this line
// Only change code below this line fact = "is awesome!";
console.log(fCC, fact); // Change this line
var sentence = str + " is cool!";
for (var i = 0; i < str.length; i+=2) {
console.log(sentence);
}
// Only change code above this line
}
printManyTimes("freeCodeCamp");
``` ```
# --solutions-- # --solutions--
```js ```js
function printManyTimes(str) { const FCC = "freeCodeCamp";
let fact = "is cool!";
const SENTENCE = str + " is cool!"; fact = "is awesome!";
for (let i = 0; i < str.length; i+=2) { console.log(FCC, fact);
console.log(SENTENCE);
}
}
printManyTimes("freeCodeCamp");
``` ```

View File

@ -9,13 +9,19 @@ dashedName: declare-string-variables
# --description-- # --description--
Anteriormente, nós usamos o código Anteriormente, você usou o seguinte código para declarar uma variável:
```js
var myName;
```
Mas você também pode declarar uma variável string assim:
```js ```js
var myName = "your name"; var myName = "your name";
``` ```
`"your name"` é chamado de <dfn>string</dfn> <dfn>literal</dfn>. É uma string porque é uma série de 0 ou mais caracteres entre aspas simples ou duplas. `"your name"` é chamado de <dfn>string</dfn> <dfn>literal</dfn>. Uma string literal, ou string, é uma série de 0 ou mais caracteres entre aspas simples ou duplas.
# --instructions-- # --instructions--

View File

@ -8,32 +8,30 @@ dashedName: explore-differences-between-the-var-and-let-keywords
# --description-- # --description--
Um dos maiores problemas ao declarar variáveis com a palavra-chave `var` é que você pode sobrescrever a declaração da variável sem perceber. Um dos maiores problemas ao declarar variáveis com a palavra-chave `var` é que você pode sobrescrever facilmente declarações de variável:
```js ```js
var camper = 'James'; var camper = "James";
var camper = 'David'; var camper = "David";
console.log(camper); console.log(camper);
``` ```
Aqui o console vai exibir a string `David`. No código acima, a variável `camper` é originalmente declarada com o valor `James` e então substituída pelo valor `David`. O console, então, vai exibir a string `David`.
Como você pode ver no código acima, a variável `camper` é originalmente declarada com o valor `James` e então substituída pelo valor `David`. Em uma aplicação pequena, você pode não encontrar esse tipo de problema, mas quando seu código se tornar maior, você pode acidentalmente sobrescrever uma variável que você não tinha a intenção. Como esse comportamento não lança nenhum erro, procurar e corrigir bugs se torna mais difícil. Em uma aplicação pequena, você pode não encontrar esse tipo de problema. Mas à medida que sua base de código se tornar maior, você pode sobrescrever acidentalmente uma variável que você não pretendia. Como esse comportamento não lança um erro, a busca e correção de bugs tornam-se mais difíceis.
Para resolver esse potencial problema com a palavra-chave `var`, uma nova palavra-chave chamada `let` foi introduzida no ES6. Se você tentar substituir `var` por `let` nas declarações de variável do código acima, o resultado será um erro.
Uma palavra-chave chamada `let` foi introduzida na ES6, uma grande atualização para o JavaScript, para resolver este possível problema com a palavra-chave `var`. Você vai aprender sobre outros recursos da ES6 em desafios posteriores.
Se você substituir `var` por `let` no código acima, ele resultará em um erro:
```js ```js
let camper = 'James'; let camper = "James";
let camper = 'David'; let camper = "David";
``` ```
Esse erro pode ser visto no console do seu navegador. Então, diferente de `var`, ao usar `let`, uma variável com o mesmo nome só pode ser declarada uma única vez. Note o `"use strict"`. Isso habilita o Modo Estrito, o qual captura erros de codificação comum e ações "não seguras". Por exemplo: O erro pode ser visto no console do seu navegador.
```js Então, diferente de `var`, ao usar `let`, uma variável com o mesmo nome só pode ser declarada uma única vez.
"use strict";
x = 3.14;
```
O código acima vai exibir o erro: `x is not defined`.
# --instructions-- # --instructions--
@ -53,10 +51,10 @@ A variável `catName` deve ser uma string de valor `Oliver`.
assert(catName === 'Oliver'); assert(catName === 'Oliver');
``` ```
A variável `quote` deve ser uma string de valor `Oliver says Meow!` `catSound` deve ser uma string de valor `Meow!`
```js ```js
assert(quote === 'Oliver says Meow!'); assert(catSound === 'Meow!');
``` ```
# --seed-- # --seed--
@ -64,28 +62,13 @@ assert(quote === 'Oliver says Meow!');
## --seed-contents-- ## --seed-contents--
```js ```js
var catName; var catName = "Oliver";
var quote; var catSound = "Meow!";
function catTalk() {
"use strict";
catName = "Oliver";
quote = catName + " says Meow!";
}
catTalk();
``` ```
# --solutions-- # --solutions--
```js ```js
let catName; let catName = "Oliver";
let quote; let catSound = "Meow!";
function catTalk() {
'use strict';
catName = 'Oliver';
quote = catName + ' says Meow!';
}
catTalk();
``` ```

View File

@ -17,7 +17,7 @@ console.log("Alan Peter".length);
O valor `10` seria exibido no console. O valor `10` seria exibido no console.
Por exemplo, se nós criássemos uma variável `var firstName = "Ada"`, poderíamos descobrir qual o tamanho da string `Ada` usando a propriedade `firstName.length`. Por exemplo, se nós criássemos uma variável `const firstName = "Ada"`, poderíamos descobrir qual o tamanho da string `Ada` usando a propriedade `firstName.length`.
# --instructions-- # --instructions--
@ -29,8 +29,8 @@ Você não deve alterar as declarações de variáveis na seção `// Setup`.
```js ```js
assert( assert(
code.match(/var lastNameLength = 0;/) && code.match(/let lastNameLength = 0;/) &&
code.match(/var lastName = "Lovelace";/) code.match(/const lastName = "Lovelace";/)
); );
``` ```
@ -52,18 +52,17 @@ assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
```js ```js
// Setup // Setup
var lastNameLength = 0; let lastNameLength = 0;
var lastName = "Lovelace"; const lastName = "Lovelace";
// Only change code below this line // Only change code below this line
lastNameLength = lastName; lastNameLength = lastName;
``` ```
# --solutions-- # --solutions--
```js ```js
var lastNameLength = 0; let lastNameLength = 0;
var lastName = "Lovelace"; const lastName = "Lovelace";
lastNameLength = lastName.length; lastNameLength = lastName.length;
``` ```

View File

@ -15,9 +15,9 @@ Variáveis que são declaradas sem a palavra-chave `var` são automaticamente cr
# --instructions-- # --instructions--
Usando `var`, declare uma variável global chamada `myGlobal` fora de qualquer função. Inicialize-a com o valor de `10`. Usando `let` ou `const`, declare uma variável global chamada `myGlobal` fora de qualquer função. Inicialize-a com o valor de `10`.
Dentro da função `fun1`, atribua `5` para `oopsGlobal` ***sem*** usar a palavra-chave `var`. Dentro da função `fun1`, atribua `5` para `oopsGlobal` ***sem*** usar as palavras-chave `let` ou `const`.
# --hints-- # --hints--
@ -33,10 +33,10 @@ assert(typeof myGlobal != 'undefined');
assert(myGlobal === 10); assert(myGlobal === 10);
``` ```
`myGlobal` deve ser declarada usando a palavra-chave `var` `myGlobal` deve ser declarada usando a palavra-chave `let` ou `const`
```js ```js
assert(/var\s+myGlobal/.test(code)); assert(/(let|const)\s+myGlobal/.test(code));
``` ```
`oopsGlobal` deve ser uma variável global e ter o valor de `5` `oopsGlobal` deve ser uma variável global e ter o valor de `5`
@ -109,7 +109,7 @@ function fun2() {
# --solutions-- # --solutions--
```js ```js
var myGlobal = 10; const myGlobal = 10;
function fun1() { function fun1() {
oopsGlobal = 5; oopsGlobal = 5;

View File

@ -14,13 +14,14 @@ Laços for não tem de iterar um de cada vez. Ao alterar nossa `final-expression
Começaremos em `i = 0` e um laço while `i < 10`. Incrementaremos `i` em 2 a cada iteração com `i += 2`. Começaremos em `i = 0` e um laço while `i < 10`. Incrementaremos `i` em 2 a cada iteração com `i += 2`.
```js ```js
var ourArray = []; const ourArray = [];
for (var i = 0; i < 10; i += 2) {
for (let i = 0; i < 10; i += 2) {
ourArray.push(i); ourArray.push(i);
} }
``` ```
`ourArray` agora conterá `[0,2,4,6,8]`. Vamos mudar nossa `initialization` para que possamos contar por números ímpares. `ourArray` agora conterá `[0, 2, 4, 6, 8]`. Vamos mudar nossa `initialization` para que possamos contar por números ímpares.
# --instructions-- # --instructions--
@ -34,7 +35,7 @@ Você deve estar usando um laço `for` para isso.
assert(/for\s*\([^)]+?\)/.test(code)); assert(/for\s*\([^)]+?\)/.test(code));
``` ```
`myArray` deve ser igual a `[1,3,5,7,9]`. `myArray` deve ser igual a `[1, 3, 5, 7, 9]`.
```js ```js
assert.deepEqual(myArray, [1, 3, 5, 7, 9]); assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
@ -52,16 +53,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js ```js
// Setup // Setup
var myArray = []; const myArray = [];
// Only change code below this line // Only change code below this line
``` ```
# --solutions-- # --solutions--
```js ```js
var myArray = []; const myArray = [];
for (var i = 1; i < 10; i += 2) { for (let i = 1; i < 10; i += 2) {
myArray.push(i); myArray.push(i);
} }
``` ```

View File

@ -26,13 +26,14 @@ A expressão final é executada no final de cada iteração do laço, antes da v
No exemplo a seguir, inicializamos com `i = 0` e iteramos enquanto nossa condição `i < 5` for verdadeira. Nós incrementaremos `i` em `1` em cada iteração do laço com `i++` como nossa expressão final. No exemplo a seguir, inicializamos com `i = 0` e iteramos enquanto nossa condição `i < 5` for verdadeira. Nós incrementaremos `i` em `1` em cada iteração do laço com `i++` como nossa expressão final.
```js ```js
var ourArray = []; const ourArray = [];
for (var i = 0; i < 5; i++) {
for (let i = 0; i < 5; i++) {
ourArray.push(i); ourArray.push(i);
} }
``` ```
`ourArray` agora terá o valor de `[0,1,2,3,4]`. `ourArray` agora terá o valor de `[0, 1, 2, 3, 4]`.
# --instructions-- # --instructions--
@ -46,7 +47,7 @@ Você deve usar um laço `for` para isso.
assert(/for\s*\([^)]+?\)/.test(code)); assert(/for\s*\([^)]+?\)/.test(code));
``` ```
`myArray` deve ser igual a `[1,2,3,4,5]`. `myArray` deve ser igual a `[1, 2, 3, 4, 5]`.
```js ```js
assert.deepEqual(myArray, [1, 2, 3, 4, 5]); assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
@ -64,16 +65,17 @@ if (typeof myArray !== "undefined"){(function(){return myArray;})();}
```js ```js
// Setup // Setup
var myArray = []; const myArray = [];
// Only change code below this line // Only change code below this line
``` ```
# --solutions-- # --solutions--
```js ```js
var myArray = []; const myArray = [];
for (var i = 1; i < 6; i++) { for (let i = 1; i < 6; i++) {
myArray.push(i); myArray.push(i);
} }
``` ```

View File

@ -14,9 +14,10 @@ Você pode rodar o mesmo código várias vezes usando um laço.
O primeiro tipo de laço que aprenderemos é chamado de laço `while` porque ele rodará enquanto uma condição específica for verdadeira e vai parar uma vez que a condição não for mais verdadeira. O primeiro tipo de laço que aprenderemos é chamado de laço `while` porque ele rodará enquanto uma condição específica for verdadeira e vai parar uma vez que a condição não for mais verdadeira.
```js ```js
var ourArray = []; const ourArray = [];
var i = 0; let i = 0;
while(i < 5) {
while (i < 5) {
ourArray.push(i); ourArray.push(i);
i++; i++;
} }
@ -38,7 +39,7 @@ Você deve usar um laço `while` para isso.
assert(code.match(/while/g)); assert(code.match(/while/g));
``` ```
`myArray` deve ser igual a `[5,4,3,2,1,0]`. `myArray` deve ser igual a `[5, 4, 3, 2, 1, 0]`.
```js ```js
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]); assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
@ -56,17 +57,18 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js ```js
// Setup // Setup
var myArray = []; const myArray = [];
// Only change code below this line // Only change code below this line
``` ```
# --solutions-- # --solutions--
```js ```js
var myArray = []; const myArray = [];
var i = 5; let i = 5;
while(i >= 0) { while (i >= 0) {
myArray.push(i); myArray.push(i);
i--; i--;
} }

View File

@ -16,8 +16,8 @@ Outra forma de alterar os dados em um array é com a função `.pop()`.
Qualquer tipo de entrada pode ser removida de um array - numbers, strings e até mesmo arrays aninhados. Qualquer tipo de entrada pode ser removida de um array - numbers, strings e até mesmo arrays aninhados.
```js ```js
var threeArr = [1, 4, 6]; const threeArr = [1, 4, 6];
var oneDown = threeArr.pop(); const oneDown = threeArr.pop();
console.log(oneDown); console.log(oneDown);
console.log(threeArr); console.log(threeArr);
``` ```
@ -26,7 +26,7 @@ O primeiro `console.log` exibirá o valor `6` e o segundo exibirá o valor `[1,
# --instructions-- # --instructions--
Use a função `.pop()` para remover o último item de `myArray`, atribuindo o valor removido para `removedFromMyArray`. Use a função `.pop()` para remover o último item de `myArray` e atribuir o valor removido para uma nova variável, `removedFromMyArray`.
# --hints-- # --hints--
@ -69,22 +69,22 @@ assert(
## --after-user-code-- ## --after-user-code--
```js ```js
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray); if (typeof removedFromMyArray !== 'undefined') (function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
``` ```
## --seed-contents-- ## --seed-contents--
```js ```js
// Setup // Setup
var myArray = [["John", 23], ["cat", 2]]; const myArray = [["John", 23], ["cat", 2]];
// Only change code below this line // Only change code below this line
var removedFromMyArray;
``` ```
# --solutions-- # --solutions--
```js ```js
var myArray = [["John", 23], ["cat", 2]]; const myArray = [["John", 23], ["cat", 2]];
var removedFromMyArray = myArray.pop(); const removedFromMyArray = myArray.pop();
``` ```

View File

@ -16,15 +16,15 @@ dashedName: manipulate-arrays-with-shift
Exemplo: Exemplo:
```js ```js
var ourArray = ["Stimpson", "J", ["cat"]]; const ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift(); const removedFromOurArray = ourArray.shift();
``` ```
`removedFromOurArray` teria o valor da string `Stimpson` e `ourArray` teria o valor de `["J", ["cat"]]`. `removedFromOurArray` teria o valor da string `Stimpson` e `ourArray` teria o valor de `["J", ["cat"]]`.
# --instructions-- # --instructions--
Use a função `.shift()` para remover o primeiro item de `myArray`, atribuindo o valor "removido" para `removedFromMyArray`. Use a função `.shift()` para remover o primeiro item de `myArray` e atribuir o valor removido para uma nova variável, `removedFromMyArray`.
# --hints-- # --hints--
@ -65,24 +65,24 @@ assert(
## --after-user-code-- ## --after-user-code--
```js ```js
(function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray); if (typeof removedFromMyArray !== 'undefined') (function(y, z){return 'myArray = ' + JSON.stringify(y) + ' & removedFromMyArray = ' + JSON.stringify(z);})(myArray, removedFromMyArray);
``` ```
## --seed-contents-- ## --seed-contents--
```js ```js
// Setup // Setup
var myArray = [["John", 23], ["dog", 3]]; const myArray = [["John", 23], ["dog", 3]];
// Only change code below this line // Only change code below this line
var removedFromMyArray;
``` ```
# --solutions-- # --solutions--
```js ```js
var myArray = [["John", 23], ["dog", 3]]; const myArray = [["John", 23], ["dog", 3]];
// Only change code below this line // Only change code below this line
var removedFromMyArray = myArray.shift(); const removedFromMyArray = myArray.shift();
``` ```

View File

@ -16,7 +16,7 @@ Você pode não apenas usar `shift` para remover elementos do início de um arra
Exemplo: Exemplo:
```js ```js
var ourArray = ["Stimpson", "J", "cat"]; const ourArray = ["Stimpson", "J", "cat"];
ourArray.shift(); ourArray.shift();
ourArray.unshift("Happy"); ourArray.unshift("Happy");
``` ```
@ -25,7 +25,7 @@ Após o `shift`, `ourArray` teria o valor `["J","cat"]`. Após o `unshift`, `our
# --instructions-- # --instructions--
Adicione `["Paul",35]` ao início da variável `myArray` usando `unshift()`. Adicione `["Paul", 35]` ao início da variável `myArray` usando `unshift()`.
# --hints-- # --hints--
@ -63,16 +63,17 @@ assert(
```js ```js
// Setup // Setup
var myArray = [["John", 23], ["dog", 3]]; const myArray = [["John", 23], ["dog", 3]];
myArray.shift(); myArray.shift();
// Only change code below this line // Only change code below this line
``` ```
# --solutions-- # --solutions--
```js ```js
var myArray = [["John", 23], ["dog", 3]]; const myArray = [["John", 23], ["dog", 3]];
myArray.shift(); myArray.shift();
myArray.unshift(["Paul", 35]); myArray.unshift(["Paul", 35]);
``` ```

View File

@ -9,12 +9,12 @@ dashedName: modify-array-data-with-indexes
# --description-- # --description--
Diferente de strings, as entradas de um array são <dfn>mutáveis</dfn> e pode ser modificadas livremente. Ao contrário das strings, as entradas de arrays são <dfn>mutáveis</dfn> e podem ser alteradas livremente, mesmo se o array foi declarado com `const`.
**Exemplo** **Exemplo**
```js ```js
var ourArray = [50,40,30]; const ourArray = [50, 40, 30];
ourArray[0] = 15; ourArray[0] = 15;
``` ```
@ -28,7 +28,7 @@ Modifique o dado armazenado no índice `0` de `myArray` para um valor de `45`.
# --hints-- # --hints--
`myArray` agora deve ser `[45,64,99]`. `myArray` agora deve ser `[45, 64, 99]`.
```js ```js
assert( assert(
@ -73,14 +73,15 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
```js ```js
// Setup // Setup
var myArray = [18,64,99]; const myArray = [18, 64, 99];
// Only change code below this line // Only change code below this line
``` ```
# --solutions-- # --solutions--
```js ```js
var myArray = [18,64,99]; const myArray = [18, 64, 99];
myArray[0] = 45; myArray[0] = 45;
``` ```

View File

@ -12,11 +12,12 @@ dashedName: nesting-for-loops
Se você possui um array multidimensional, você pode usar a mesma lógica no ponto de passagem anterior para iterar através de arrays e de qualquer sub-array. Exemplo: Se você possui um array multidimensional, você pode usar a mesma lógica no ponto de passagem anterior para iterar através de arrays e de qualquer sub-array. Exemplo:
```js ```js
var arr = [ const arr = [
[1,2], [3,4], [5,6] [1, 2], [3, 4], [5, 6]
]; ];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) { for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
console.log(arr[i][j]); console.log(arr[i][j]);
} }
} }
@ -30,13 +31,13 @@ Modifique a função `multiplyAll` para que retorne o produto de todos os númer
# --hints-- # --hints--
`multiplyAll([[1],[2],[3]])` deve retornar `6` `multiplyAll([[1], [2], [3]])` deve retornar `6`
```js ```js
assert(multiplyAll([[1], [2], [3]]) === 6); assert(multiplyAll([[1], [2], [3]]) === 6);
``` ```
`multiplyAll([[1,2],[3,4],[5,6,7]])` deve retornar `5040` `multiplyAll([[1, 2], [3, 4], [5, 6, 7]])` deve retornar `5040`
```js ```js
assert( assert(
@ -48,7 +49,7 @@ assert(
); );
``` ```
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` deve retornar `54` `multiplyAll([[5, 1], [0.2, 4, 0.5], [3, 9]])` deve retornar `54`
```js ```js
assert( assert(
@ -66,28 +67,26 @@ assert(
```js ```js
function multiplyAll(arr) { function multiplyAll(arr) {
var product = 1; let product = 1;
// Only change code below this line // Only change code below this line
// Only change code above this line // Only change code above this line
return product; return product;
} }
multiplyAll([[1,2],[3,4],[5,6,7]]); multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
``` ```
# --solutions-- # --solutions--
```js ```js
function multiplyAll(arr) { function multiplyAll(arr) {
var product = 1; let product = 1;
for (var i = 0; i < arr.length; i++) { for (let i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; j++) { for (let j = 0; j < arr[i].length; j++) {
product *= arr[i][j]; product *= arr[i][j];
} }
} }
return product; return product;
} }
multiplyAll([[1,2],[3,4],[5,6,7]]);
``` ```

View File

@ -33,43 +33,43 @@ Lembre-se de que [`undefined` é uma palavra-chave](https://www.freecodecamp.org
# --hints-- # --hints--
`abTest(2,2)` deve retornar um número `abTest(2, 2)` deve retornar um número
```js ```js
assert(typeof abTest(2, 2) === 'number'); assert(typeof abTest(2, 2) === 'number');
``` ```
`abTest(2,2)` deve retornar `8` `abTest(2, 2)` deve retornar `8`
```js ```js
assert(abTest(2, 2) === 8); assert(abTest(2, 2) === 8);
``` ```
`abTest(-2,2)` deve retornar `undefined` `abTest(-2, 2)` deve retornar `undefined`
```js ```js
assert(abTest(-2, 2) === undefined); assert(abTest(-2, 2) === undefined);
``` ```
`abTest(2,-2)` deve retornar `undefined` `abTest(2, -2)` deve retornar `undefined`
```js ```js
assert(abTest(2, -2) === undefined); assert(abTest(2, -2) === undefined);
``` ```
`abTest(2,8)` deve retornar `18` `abTest(2, 8)` deve retornar `18`
```js ```js
assert(abTest(2, 8) === 18); assert(abTest(2, 8) === 18);
``` ```
`abTest(3,3)` deve retornar `12` `abTest(3, 3)` deve retornar `12`
```js ```js
assert(abTest(3, 3) === 12); assert(abTest(3, 3) === 12);
``` ```
`abTest(0,0)` deve retornar `0` `abTest(0, 0)` deve retornar `0`
```js ```js
assert(abTest(0, 0) === 0); assert(abTest(0, 0) === 0);

View File

@ -14,7 +14,7 @@ Você pode se lembrar de [Comparação com o operador de igualdade](/learn/javas
Às vezes, as pessoas usam uma instrução `if/else` para fazer uma comparação, dessa forma: Às vezes, as pessoas usam uma instrução `if/else` para fazer uma comparação, dessa forma:
```js ```js
function isEqual(a,b) { function isEqual(a, b) {
if (a === b) { if (a === b) {
return true; return true;
} else { } else {
@ -26,7 +26,7 @@ function isEqual(a,b) {
Mas há uma forma melhor de fazer isso. Já que `===` retorna `true` ou `false`, podemos retornar o resultado da comparação: Mas há uma forma melhor de fazer isso. Já que `===` retorna `true` ou `false`, podemos retornar o resultado da comparação:
```js ```js
function isEqual(a,b) { function isEqual(a, b) {
return a === b; return a === b;
} }
``` ```
@ -37,13 +37,13 @@ Corrija a função `isLess` para remover as instruções `if/else`.
# --hints-- # --hints--
`isLess(10,15)` deve retornar `true` `isLess(10, 15)` deve retornar `true`
```js ```js
assert(isLess(10, 15) === true); assert(isLess(10, 15) === true);
``` ```
`isLess(15,10)` deve retornar `false` `isLess(15, 10)` deve retornar `false`
```js ```js
assert(isLess(15, 10) === false); assert(isLess(15, 10) === false);

View File

@ -13,13 +13,13 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
A maioria das linguagens de programação modernas, como JavaScript, não começa contando do 1 como humanos fazem. Elas começam no 0. Isso é referido como indexação <dfn>baseada em zero</dfn>. A maioria das linguagens de programação modernas, como JavaScript, não começa contando do 1 como humanos fazem. Elas começam no 0. Isso é referido como indexação <dfn>baseada em zero</dfn>.
Por exemplo, o caractere no índice 0 da palavra `Charles` é `C`. Então, se `var firstName = "Charles"`, você pode pegar o valor da primeira letra da string usando `firstName[0]`. Por exemplo, o caractere no índice 0 da palavra `Charles` é `C`. Então, se `const firstName = "Charles"`, você pode pegar o valor da primeira letra da string usando `firstName[0]`.
Exemplo: Exemplo:
```js ```js
var firstName = "Charles"; const firstName = "Charles";
var firstLetter = firstName[0]; const firstLetter = firstName[0];
``` ```
`firstLetter` teria o valor da string `C`. `firstLetter` teria o valor da string `C`.
@ -56,8 +56,8 @@ assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
```js ```js
// Setup // Setup
var firstLetterOfLastName = ""; let firstLetterOfLastName = "";
var lastName = "Lovelace"; const lastName = "Lovelace";
// Only change code below this line // Only change code below this line
firstLetterOfLastName = lastName; // Change this line firstLetterOfLastName = lastName; // Change this line
@ -66,8 +66,8 @@ firstLetterOfLastName = lastName; // Change this line
# --solutions-- # --solutions--
```js ```js
var firstLetterOfLastName = ""; let firstLetterOfLastName = "";
var lastName = "Lovelace"; const lastName = "Lovelace";
// Only change code below this line // Only change code below this line
firstLetterOfLastName = lastName[0]; firstLetterOfLastName = lastName[0];

View File

@ -11,13 +11,13 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
Para pegar a última letra de uma string, você pode subtrair um do tamanho da string. Para pegar a última letra de uma string, você pode subtrair um do tamanho da string.
Por exemplo, se `var firstName = "Ada"`, você pode pegar o valor da última letra da string ao usar `firstName[firstName.length - 1]`. Por exemplo, se `const firstName = "Ada"`, você pode pegar o valor da última letra da string ao usar `firstName[firstName.length - 1]`.
Exemplo: Exemplo:
```js ```js
var firstName = "Ada"; const firstName = "Ada";
var lastLetter = firstName[firstName.length - 1]; const lastLetter = firstName[firstName.length - 1];
``` ```
`lastLetter` teria o valor da string `a`. `lastLetter` teria o valor da string `a`.
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
```js ```js
// Setup // Setup
var lastName = "Lovelace"; const lastName = "Lovelace";
// Only change code below this line // Only change code below this line
var lastLetterOfLastName = lastName; // Change this line const lastLetterOfLastName = lastName; // Change this line
``` ```
# --solutions-- # --solutions--
```js ```js
var lastName = "Lovelace"; const lastName = "Lovelace";
var lastLetterOfLastName = lastName[lastName.length - 1]; const lastLetterOfLastName = lastName[lastName.length - 1];
``` ```

View File

@ -11,13 +11,13 @@ dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string
Você pode usar o mesmo princípio que nós acabamos de usar para recuperar o último caractere em uma string, para recuperar o enésimo caractere antes do último caractere. Você pode usar o mesmo princípio que nós acabamos de usar para recuperar o último caractere em uma string, para recuperar o enésimo caractere antes do último caractere.
Por exemplo, você pode pegar o valor da antepenúltima letra da string `var firstName = "Augusta"` usando `firstName[firstName.length - 3]` Por exemplo, você pode pegar o valor da antepenúltima letra da string `const firstName = "Augusta"` usando `firstName[firstName.length - 3]`
Exemplo: Exemplo:
```js ```js
var firstName = "Augusta"; const firstName = "Augusta";
var thirdToLastLetter = firstName[firstName.length - 3]; const thirdToLastLetter = firstName[firstName.length - 3];
``` ```
`thirdToLastLetter` teria o valor da string `s`. `thirdToLastLetter` teria o valor da string `s`.
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
```js ```js
// Setup // Setup
var lastName = "Lovelace"; const lastName = "Lovelace";
// Only change code below this line // Only change code below this line
var secondToLastLetterOfLastName = lastName; // Change this line const secondToLastLetterOfLastName = lastName; // Change this line
``` ```
# --solutions-- # --solutions--
```js ```js
var lastName = "Lovelace"; const lastName = "Lovelace";
var secondToLastLetterOfLastName = lastName[lastName.length - 2]; const secondToLastLetterOfLastName = lastName[lastName.length - 2];
``` ```

View File

@ -9,7 +9,7 @@ dashedName: use-conditional-logic-with-if-statements
# --description-- # --description--
Instruções `If` são usadas para tomar decisões no código. A palavra-chave `if` diz ao JavaScript para executar o código nas chaves sob certas condições, definidas nos parênteses. Essas condições são conhecidas como condições `Boolean` e elas só podem ser `true` ou `false`. instruções `if` são usadas para tomar decisões no código. A palavra-chave `if` diz ao JavaScript para executar o código nas chaves sob certas condições, definidas nos parênteses. Essas condições são conhecidas como condições `Boolean` e elas só podem ser `true` ou `false`.
Quando a condição for `true`, o programa executará as instruções dentro das chaves. Quando a condição booleana for `false`, as instruções dentro das chaves não serão executadas. Quando a condição for `true`, o programa executará as instruções dentro das chaves. Quando a condição booleana for `false`, as instruções dentro das chaves não serão executadas.
@ -22,10 +22,11 @@ Quando a condição for `true`, o programa executará as instruções dentro das
```js ```js
function test (myCondition) { function test (myCondition) {
if (myCondition) { if (myCondition) {
return "It was true"; return "It was true";
} }
return "It was false"; return "It was false";
} }
test(true); test(true);
test(false); test(false);
``` ```

View File

@ -8,6 +8,8 @@ dashedName: compare-scopes-of-the-var-and-let-keywords
# --description-- # --description--
Se você não estiver familiarizado com `let`, confira [este desafio](/learn/javascript-algorithms-and-data-structures/basic-javascript/explore-differences-between-the-var-and-let-keywords).
Quando você declara uma variável com a palavra-chave `var`, ela é declarada globalmente, ou localmente se declarada dentro de uma função. Quando você declara uma variável com a palavra-chave `var`, ela é declarada globalmente, ou localmente se declarada dentro de uma função.
A palavra-chave `let` se comporta de forma similar, mas com alguns recursos extras. Quando você declara a variável com a palavra-chave `let` dentro de um bloco, declaração, ou expressão, seu escopo é limitado ao bloco, declaração, ou expressão. A palavra-chave `let` se comporta de forma similar, mas com alguns recursos extras. Quando você declara a variável com a palavra-chave `let` dentro de um bloco, declaração, ou expressão, seu escopo é limitado ao bloco, declaração, ou expressão.

View File

@ -8,6 +8,8 @@ dashedName: mutate-an-array-declared-with-const
# --description-- # --description--
Se você não estiver familiarizado com `const`, confira [este desafio](/learn/javascript-algorithms-and-data-structures/basic-javascript/declare-a-read-only-variable-with-the-const-keyword).
Variáveis declaradas com `const` têm muitos casos de uso no JavaScript moderno. Variáveis declaradas com `const` têm muitos casos de uso no JavaScript moderno.
Alguns desenvolvedores preferem criar todas suas variáveis usando `const`, a menos que eles saibam que vão precisar reatribuir o valor. Apenas nesse caso, eles usam `let`. Alguns desenvolvedores preferem criar todas suas variáveis usando `const`, a menos que eles saibam que vão precisar reatribuir o valor. Apenas nesse caso, eles usam `let`.

View File

@ -10,7 +10,7 @@ dashedName: refactor-global-variables-out-of-functions
Até agora vimos dois princípios diferentes de programação funcional: Até agora vimos dois princípios diferentes de programação funcional:
1) Não altere variáveis ou objetos: crie novas variáveis ou objetos e os retorne, caso necessário, de uma função. Dica: escrever algo como `var newArr = arrVar` onde `arrVar` é um array não o copiará para a nova a variável, e sim apenas criará uma nova referência ao mesmo objeto. Então mudar um valor em `newArr` também o muda em `arrVar`. 1) Não altere variáveis ou objetos: crie novas variáveis ou objetos e os retorne, caso necessário, de uma função. Dica: escrever algo como `const newArr = arrVar` onde `arrVar` é um array não o copiará para a nova a variável, e sim apenas criará uma nova referência ao mesmo objeto. Então mudar um valor em `newArr` também o muda em `arrVar`.
2) Declare parâmetros de funções: qualquer computação dentro de uma função depende apenas dos argumentos passados a ela; nunca de uma variável ou objeto global. 2) Declare parâmetros de funções: qualquer computação dentro de uma função depende apenas dos argumentos passados a ela; nunca de uma variável ou objeto global.
@ -86,7 +86,7 @@ assert(
```js ```js
// The global variable // The global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]; const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
// Change code below this line // Change code below this line
function add (bookName) { function add (bookName) {
@ -99,7 +99,7 @@ function add (bookName) {
// Change code below this line // Change code below this line
function remove (bookName) { function remove (bookName) {
var book_index = bookList.indexOf(bookName); const book_index = bookList.indexOf(bookName);
if (book_index >= 0) { if (book_index >= 0) {
bookList.splice(book_index, 1); bookList.splice(book_index, 1);
@ -109,9 +109,9 @@ function remove (bookName) {
} }
} }
var newBookList = add(bookList, 'A Brief History of Time'); const newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies'); const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies'); const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
console.log(bookList); console.log(bookList);
``` ```
@ -120,13 +120,13 @@ console.log(bookList);
```js ```js
// The global variable // The global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"]; const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
function add (bookList, bookName) { function add(bookList, bookName) {
return [...bookList, bookName]; return [...bookList, bookName];
} }
function remove (bookList, bookName) { function remove(bookList, bookName) {
const bookListCopy = [...bookList]; const bookListCopy = [...bookList];
const bookNameIndex = bookList.indexOf(bookName); const bookNameIndex = bookList.indexOf(bookName);
if (bookNameIndex >= 0) { if (bookNameIndex >= 0) {
@ -135,7 +135,7 @@ function remove (bookList, bookName) {
return bookListCopy; return bookListCopy;
} }
var newBookList = add(bookList, 'A Brief History of Time'); const newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies'); const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies'); const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
``` ```

View File

@ -55,7 +55,7 @@ Você não deve usar loops `for`.
assert(!code.match(/for\s*?\([\s\S]*?\)/g)); assert(!code.match(/for\s*?\([\s\S]*?\)/g));
``` ```
`filteredList` deve ser igual a `[{"title": "Inception","rating": "8.8"},{"title": "Interstellar","rating": "8.6"},{"title": "The Dark Knight","rating": "9.0"},{"title": "Batman Begins","rating": "8.3"}]`. `filteredList` deve ser igual a `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"}, {"title": "Batman Begins", "rating": "8.3"}]`.
```js ```js
assert.deepEqual(filteredList, [ assert.deepEqual(filteredList, [
@ -72,7 +72,7 @@ assert.deepEqual(filteredList, [
```js ```js
// The global variable // The global variable
var watchList = [ const watchList = [
{ {
"Title": "Inception", "Title": "Inception",
"Year": "2010", "Year": "2010",
@ -187,7 +187,7 @@ var watchList = [
// Only change code below this line // Only change code below this line
var filteredList; const filteredList = "";
// Only change code above this line // Only change code above this line
@ -197,8 +197,7 @@ console.log(filteredList);
# --solutions-- # --solutions--
```js ```js
// The global variable const watchList = [
var watchList = [
{ {
"Title": "Inception", "Title": "Inception",
"Year": "2010", "Year": "2010",
@ -311,7 +310,5 @@ var watchList = [
} }
]; ];
// Only change code below this line const filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
let filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
// Only change code above this line
``` ```

View File

@ -61,7 +61,7 @@ Você deve usar o método `map`.
assert(code.match(/\.map/g)); assert(code.match(/\.map/g));
``` ```
`ratings` deve ser igual a `[{"title":"Inception","rating":"8.8"},{"title":"Interstellar","rating":"8.6"},{"title":"The Dark Knight","rating":"9.0"},{"title":"Batman Begins","rating":"8.3"},{"title":"Avatar","rating":"7.9"}]`. `ratings` deve ser igual a `[{"title": "Inception", "rating": "8.8"}, {"title": "Interstellar", "rating": "8.6"}, {"title": "The Dark Knight", "rating": "9.0"},{"title": "Batman Begins", "rating": "8.3"}, {"title": "Avatar", "rating": "7.9"}]`.
```js ```js
assert.deepEqual(ratings, [ assert.deepEqual(ratings, [
@ -79,7 +79,7 @@ assert.deepEqual(ratings, [
```js ```js
// The global variable // The global variable
var watchList = [ const watchList = [
{ {
"Title": "Inception", "Title": "Inception",
"Year": "2010", "Year": "2010",
@ -194,9 +194,9 @@ var watchList = [
// Only change code below this line // Only change code below this line
var ratings = []; const ratings = [];
for(var i=0; i < watchList.length; i++){ for (let i = 0; i < watchList.length; i++) {
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]}); ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
} }
// Only change code above this line // Only change code above this line
@ -207,8 +207,7 @@ console.log(JSON.stringify(ratings));
# --solutions-- # --solutions--
```js ```js
// The global variable const watchList = [
var watchList = [
{ {
"Title": "Inception", "Title": "Inception",
"Year": "2010", "Year": "2010",
@ -321,7 +320,7 @@ var watchList = [
} }
]; ];
var ratings = watchList.map(function(movie) { const ratings = watchList.map(function(movie) {
return { return {
title: movie["Title"], title: movie["Title"],
rating: movie["imdbRating"] rating: movie["imdbRating"]