chore(i18n,curriculum): update translations (#44114)
This commit is contained in:
@ -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 #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"`.
|
||||
|
||||
|
@ -25,7 +25,7 @@ Em ordem, essas expressões seriam iguais à `true`, `false`, `false`, `false` e
|
||||
|
||||
# --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--
|
||||
|
||||
|
@ -26,7 +26,7 @@ No segundo exemplo, `3` é um tipo de `Number` e `'3'` é um tipo `String`.
|
||||
|
||||
# --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--
|
||||
|
||||
|
@ -22,7 +22,7 @@ Em JavaScript, quando o operador `+` é usado com um valor de `String`, ele é c
|
||||
Exemplo:
|
||||
|
||||
```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.
|
||||
@ -44,10 +44,10 @@ Você deve usar o operador `+` para criar `myStr`.
|
||||
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
|
||||
assert(/var\s+myStr/.test(code));
|
||||
assert(/const\s+myStr/.test(code));
|
||||
```
|
||||
|
||||
Você deve atribuir o resultado à variável `myStr`.
|
||||
@ -73,11 +73,11 @@ assert(/myStr\s*=/.test(code));
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var myStr; // Change this line
|
||||
const myStr = ""; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myStr = "This is the start. " + "This is the end.";
|
||||
const myStr = "This is the start. " + "This is the end.";
|
||||
```
|
||||
|
@ -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`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 10; i > 0; i -= 2) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 10; i > 0; i -= 2) {
|
||||
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--
|
||||
|
||||
@ -42,7 +43,7 @@ Você deve usar o método de array `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
|
||||
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
|
||||
@ -60,16 +61,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 9; i > 0; i -= 2) {
|
||||
const myArray = [];
|
||||
for (let i = 9; i > 0; i -= 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -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`.
|
||||
|
||||
`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
|
||||
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`.
|
||||
|
||||
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--
|
||||
|
||||
@ -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));
|
||||
```
|
||||
|
||||
`SENTENCE` deve ser uma variável constante declarada com `const`.
|
||||
Você deve alterar `fCC` para uma string toda em letras maiúsculas.
|
||||
|
||||
```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
|
||||
(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
|
||||
(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--
|
||||
@ -59,31 +71,18 @@ A variável `i` deve ser declarada com `let`.
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function printManyTimes(str) {
|
||||
|
||||
// Only change code below 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");
|
||||
var fCC = "freeCodeCamp"; // Change this line
|
||||
var fact = "is cool!"; // Change this line
|
||||
fact = "is awesome!";
|
||||
console.log(fCC, fact); // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function printManyTimes(str) {
|
||||
const FCC = "freeCodeCamp";
|
||||
let fact = "is cool!";
|
||||
|
||||
const SENTENCE = str + " is cool!";
|
||||
for (let i = 0; i < str.length; i+=2) {
|
||||
console.log(SENTENCE);
|
||||
}
|
||||
|
||||
}
|
||||
printManyTimes("freeCodeCamp");
|
||||
fact = "is awesome!";
|
||||
console.log(FCC, fact);
|
||||
```
|
||||
|
@ -9,13 +9,19 @@ dashedName: declare-string-variables
|
||||
|
||||
# --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
|
||||
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--
|
||||
|
||||
|
@ -8,32 +8,30 @@ dashedName: explore-differences-between-the-var-and-let-keywords
|
||||
|
||||
# --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
|
||||
var camper = 'James';
|
||||
var camper = 'David';
|
||||
var camper = "James";
|
||||
var camper = "David";
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
|
||||
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
|
||||
let camper = 'James';
|
||||
let camper = 'David';
|
||||
let camper = "James";
|
||||
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
|
||||
"use strict";
|
||||
x = 3.14;
|
||||
```
|
||||
|
||||
O código acima vai exibir o erro: `x is not defined`.
|
||||
Então, diferente de `var`, ao usar `let`, uma variável com o mesmo nome só pode ser declarada uma única vez.
|
||||
|
||||
# --instructions--
|
||||
|
||||
@ -53,10 +51,10 @@ A variável `catName` deve ser uma string de valor `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
|
||||
assert(quote === 'Oliver says Meow!');
|
||||
assert(catSound === 'Meow!');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -64,28 +62,13 @@ assert(quote === 'Oliver says Meow!');
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
var catName;
|
||||
var quote;
|
||||
function catTalk() {
|
||||
"use strict";
|
||||
|
||||
catName = "Oliver";
|
||||
quote = catName + " says Meow!";
|
||||
|
||||
}
|
||||
catTalk();
|
||||
var catName = "Oliver";
|
||||
var catSound = "Meow!";
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let catName;
|
||||
let quote;
|
||||
function catTalk() {
|
||||
'use strict';
|
||||
|
||||
catName = 'Oliver';
|
||||
quote = catName + ' says Meow!';
|
||||
}
|
||||
catTalk();
|
||||
let catName = "Oliver";
|
||||
let catSound = "Meow!";
|
||||
```
|
||||
|
@ -17,7 +17,7 @@ console.log("Alan Peter".length);
|
||||
|
||||
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--
|
||||
|
||||
@ -29,8 +29,8 @@ Você não deve alterar as declarações de variáveis na seção `// Setup`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
code.match(/var lastNameLength = 0;/) &&
|
||||
code.match(/var lastName = "Lovelace";/)
|
||||
code.match(/let lastNameLength = 0;/) &&
|
||||
code.match(/const lastName = "Lovelace";/)
|
||||
);
|
||||
```
|
||||
|
||||
@ -52,18 +52,17 @@ assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
let lastNameLength = 0;
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
lastNameLength = lastName;
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastNameLength = 0;
|
||||
var lastName = "Lovelace";
|
||||
let lastNameLength = 0;
|
||||
const lastName = "Lovelace";
|
||||
lastNameLength = lastName.length;
|
||||
```
|
||||
|
@ -15,9 +15,9 @@ Variáveis que são declaradas sem a palavra-chave `var` são automaticamente cr
|
||||
|
||||
# --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--
|
||||
|
||||
@ -33,10 +33,10 @@ assert(typeof myGlobal != 'undefined');
|
||||
assert(myGlobal === 10);
|
||||
```
|
||||
|
||||
`myGlobal` deve ser declarada usando a palavra-chave `var`
|
||||
`myGlobal` deve ser declarada usando a palavra-chave `let` ou `const`
|
||||
|
||||
```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`
|
||||
@ -109,7 +109,7 @@ function fun2() {
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myGlobal = 10;
|
||||
const myGlobal = 10;
|
||||
|
||||
function fun1() {
|
||||
oopsGlobal = 5;
|
||||
|
@ -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`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 10; i += 2) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 0; i < 10; i += 2) {
|
||||
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--
|
||||
|
||||
@ -34,7 +35,7 @@ Você deve estar usando um laço `for` para isso.
|
||||
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
|
||||
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
||||
@ -52,16 +53,17 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 10; i += 2) {
|
||||
const myArray = [];
|
||||
for (let i = 1; i < 10; i += 2) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -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.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
for (var i = 0; i < 5; i++) {
|
||||
const ourArray = [];
|
||||
|
||||
for (let i = 0; i < 5; 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--
|
||||
|
||||
@ -46,7 +47,7 @@ Você deve usar um laço `for` para isso.
|
||||
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
|
||||
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
|
||||
@ -64,16 +65,17 @@ if (typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
for (var i = 1; i < 6; i++) {
|
||||
const myArray = [];
|
||||
for (let i = 1; i < 6; i++) {
|
||||
myArray.push(i);
|
||||
}
|
||||
```
|
||||
|
@ -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.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
var i = 0;
|
||||
while(i < 5) {
|
||||
const ourArray = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < 5) {
|
||||
ourArray.push(i);
|
||||
i++;
|
||||
}
|
||||
@ -38,7 +39,7 @@ Você deve usar um laço `while` para isso.
|
||||
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
|
||||
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
|
||||
@ -56,17 +57,18 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [];
|
||||
const myArray = [];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [];
|
||||
var i = 5;
|
||||
while(i >= 0) {
|
||||
const myArray = [];
|
||||
let i = 5;
|
||||
while (i >= 0) {
|
||||
myArray.push(i);
|
||||
i--;
|
||||
}
|
||||
|
@ -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.
|
||||
|
||||
```js
|
||||
var threeArr = [1, 4, 6];
|
||||
var oneDown = threeArr.pop();
|
||||
const threeArr = [1, 4, 6];
|
||||
const oneDown = threeArr.pop();
|
||||
console.log(oneDown);
|
||||
console.log(threeArr);
|
||||
```
|
||||
@ -26,7 +26,7 @@ O primeiro `console.log` exibirá o valor `6` e o segundo exibirá o valor `[1,
|
||||
|
||||
# --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--
|
||||
|
||||
@ -69,22 +69,22 @@ assert(
|
||||
## --after-user-code--
|
||||
|
||||
```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--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
const myArray = [["John", 23], ["cat", 2]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["cat", 2]];
|
||||
var removedFromMyArray = myArray.pop();
|
||||
const myArray = [["John", 23], ["cat", 2]];
|
||||
const removedFromMyArray = myArray.pop();
|
||||
```
|
||||
|
@ -16,15 +16,15 @@ dashedName: manipulate-arrays-with-shift
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", ["cat"]];
|
||||
var removedFromOurArray = ourArray.shift();
|
||||
const ourArray = ["Stimpson", "J", ["cat"]];
|
||||
const removedFromOurArray = ourArray.shift();
|
||||
```
|
||||
|
||||
`removedFromOurArray` teria o valor da string `Stimpson` e `ourArray` teria o valor de `["J", ["cat"]]`.
|
||||
|
||||
# --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--
|
||||
|
||||
@ -65,24 +65,24 @@ assert(
|
||||
## --after-user-code--
|
||||
|
||||
```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--
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray;
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
|
||||
// Only change code below this line
|
||||
var removedFromMyArray = myArray.shift();
|
||||
const removedFromMyArray = myArray.shift();
|
||||
```
|
||||
|
@ -16,7 +16,7 @@ Você pode não apenas usar `shift` para remover elementos do início de um arra
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", "cat"];
|
||||
const ourArray = ["Stimpson", "J", "cat"];
|
||||
ourArray.shift();
|
||||
ourArray.unshift("Happy");
|
||||
```
|
||||
@ -25,7 +25,7 @@ Após o `shift`, `ourArray` teria o valor `["J","cat"]`. Após o `unshift`, `our
|
||||
|
||||
# --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--
|
||||
|
||||
@ -63,16 +63,17 @@ assert(
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [["John", 23], ["dog", 3]];
|
||||
const myArray = [["John", 23], ["dog", 3]];
|
||||
myArray.shift();
|
||||
myArray.unshift(["Paul", 35]);
|
||||
```
|
||||
|
@ -9,12 +9,12 @@ dashedName: modify-array-data-with-indexes
|
||||
|
||||
# --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**
|
||||
|
||||
```js
|
||||
var ourArray = [50,40,30];
|
||||
const ourArray = [50, 40, 30];
|
||||
ourArray[0] = 15;
|
||||
```
|
||||
|
||||
@ -28,7 +28,7 @@ Modifique o dado armazenado no índice `0` de `myArray` para um valor de `45`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` agora deve ser `[45,64,99]`.
|
||||
`myArray` agora deve ser `[45, 64, 99]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -73,14 +73,15 @@ if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var myArray = [18,64,99];
|
||||
const myArray = [18, 64, 99];
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var myArray = [18,64,99];
|
||||
const myArray = [18, 64, 99];
|
||||
myArray[0] = 45;
|
||||
```
|
||||
|
@ -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:
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
[1,2], [3,4], [5,6]
|
||||
const arr = [
|
||||
[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]);
|
||||
}
|
||||
}
|
||||
@ -30,13 +31,13 @@ Modifique a função `multiplyAll` para que retorne o produto de todos os númer
|
||||
|
||||
# --hints--
|
||||
|
||||
`multiplyAll([[1],[2],[3]])` deve retornar `6`
|
||||
`multiplyAll([[1], [2], [3]])` deve retornar `6`
|
||||
|
||||
```js
|
||||
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
|
||||
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
|
||||
assert(
|
||||
@ -66,28 +67,26 @@ assert(
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
let product = 1;
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
return product;
|
||||
}
|
||||
|
||||
multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
multiplyAll([[1, 2], [3, 4], [5, 6, 7]]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function multiplyAll(arr) {
|
||||
var product = 1;
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
for (var j = 0; j < arr[i].length; j++) {
|
||||
let product = 1;
|
||||
for (let i = 0; i < arr.length; i++) {
|
||||
for (let j = 0; j < arr[i].length; j++) {
|
||||
product *= arr[i][j];
|
||||
}
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
multiplyAll([[1,2],[3,4],[5,6,7]]);
|
||||
```
|
||||
|
@ -33,43 +33,43 @@ Lembre-se de que [`undefined` é uma palavra-chave](https://www.freecodecamp.org
|
||||
|
||||
# --hints--
|
||||
|
||||
`abTest(2,2)` deve retornar um número
|
||||
`abTest(2, 2)` deve retornar um número
|
||||
|
||||
```js
|
||||
assert(typeof abTest(2, 2) === 'number');
|
||||
```
|
||||
|
||||
`abTest(2,2)` deve retornar `8`
|
||||
`abTest(2, 2)` deve retornar `8`
|
||||
|
||||
```js
|
||||
assert(abTest(2, 2) === 8);
|
||||
```
|
||||
|
||||
`abTest(-2,2)` deve retornar `undefined`
|
||||
`abTest(-2, 2)` deve retornar `undefined`
|
||||
|
||||
```js
|
||||
assert(abTest(-2, 2) === undefined);
|
||||
```
|
||||
|
||||
`abTest(2,-2)` deve retornar `undefined`
|
||||
`abTest(2, -2)` deve retornar `undefined`
|
||||
|
||||
```js
|
||||
assert(abTest(2, -2) === undefined);
|
||||
```
|
||||
|
||||
`abTest(2,8)` deve retornar `18`
|
||||
`abTest(2, 8)` deve retornar `18`
|
||||
|
||||
```js
|
||||
assert(abTest(2, 8) === 18);
|
||||
```
|
||||
|
||||
`abTest(3,3)` deve retornar `12`
|
||||
`abTest(3, 3)` deve retornar `12`
|
||||
|
||||
```js
|
||||
assert(abTest(3, 3) === 12);
|
||||
```
|
||||
|
||||
`abTest(0,0)` deve retornar `0`
|
||||
`abTest(0, 0)` deve retornar `0`
|
||||
|
||||
```js
|
||||
assert(abTest(0, 0) === 0);
|
||||
|
@ -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:
|
||||
|
||||
```js
|
||||
function isEqual(a,b) {
|
||||
function isEqual(a, b) {
|
||||
if (a === b) {
|
||||
return true;
|
||||
} 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:
|
||||
|
||||
```js
|
||||
function isEqual(a,b) {
|
||||
function isEqual(a, b) {
|
||||
return a === b;
|
||||
}
|
||||
```
|
||||
@ -37,13 +37,13 @@ Corrija a função `isLess` para remover as instruções `if/else`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isLess(10,15)` deve retornar `true`
|
||||
`isLess(10, 15)` deve retornar `true`
|
||||
|
||||
```js
|
||||
assert(isLess(10, 15) === true);
|
||||
```
|
||||
|
||||
`isLess(15,10)` deve retornar `false`
|
||||
`isLess(15, 10)` deve retornar `false`
|
||||
|
||||
```js
|
||||
assert(isLess(15, 10) === false);
|
||||
|
@ -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>.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
var firstName = "Charles";
|
||||
var firstLetter = firstName[0];
|
||||
const firstName = "Charles";
|
||||
const firstLetter = firstName[0];
|
||||
```
|
||||
|
||||
`firstLetter` teria o valor da string `C`.
|
||||
@ -56,8 +56,8 @@ assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
let firstLetterOfLastName = "";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName; // Change this line
|
||||
@ -66,8 +66,8 @@ firstLetterOfLastName = lastName; // Change this line
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var firstLetterOfLastName = "";
|
||||
var lastName = "Lovelace";
|
||||
let firstLetterOfLastName = "";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
firstLetterOfLastName = lastName[0];
|
||||
|
@ -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.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
var firstName = "Ada";
|
||||
var lastLetter = firstName[firstName.length - 1];
|
||||
const firstName = "Ada";
|
||||
const lastLetter = firstName[firstName.length - 1];
|
||||
```
|
||||
|
||||
`lastLetter` teria o valor da string `a`.
|
||||
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var lastLetterOfLastName = lastName; // Change this line
|
||||
const lastLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var lastLetterOfLastName = lastName[lastName.length - 1];
|
||||
const lastName = "Lovelace";
|
||||
const lastLetterOfLastName = lastName[lastName.length - 1];
|
||||
```
|
||||
|
@ -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.
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
var firstName = "Augusta";
|
||||
var thirdToLastLetter = firstName[firstName.length - 3];
|
||||
const firstName = "Augusta";
|
||||
const thirdToLastLetter = firstName[firstName.length - 3];
|
||||
```
|
||||
|
||||
`thirdToLastLetter` teria o valor da string `s`.
|
||||
@ -54,15 +54,15 @@ assert(code.match(/\.length/g).length > 0);
|
||||
|
||||
```js
|
||||
// Setup
|
||||
var lastName = "Lovelace";
|
||||
const lastName = "Lovelace";
|
||||
|
||||
// Only change code below this line
|
||||
var secondToLastLetterOfLastName = lastName; // Change this line
|
||||
const secondToLastLetterOfLastName = lastName; // Change this line
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
var lastName = "Lovelace";
|
||||
var secondToLastLetterOfLastName = lastName[lastName.length - 2];
|
||||
const lastName = "Lovelace";
|
||||
const secondToLastLetterOfLastName = lastName[lastName.length - 2];
|
||||
```
|
||||
|
@ -9,7 +9,7 @@ dashedName: use-conditional-logic-with-if-statements
|
||||
|
||||
# --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.
|
||||
|
||||
@ -22,10 +22,11 @@ Quando a condição for `true`, o programa executará as instruções dentro das
|
||||
```js
|
||||
function test (myCondition) {
|
||||
if (myCondition) {
|
||||
return "It was true";
|
||||
return "It was true";
|
||||
}
|
||||
return "It was false";
|
||||
}
|
||||
|
||||
test(true);
|
||||
test(false);
|
||||
```
|
||||
|
@ -8,6 +8,8 @@ dashedName: compare-scopes-of-the-var-and-let-keywords
|
||||
|
||||
# --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.
|
||||
|
||||
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.
|
||||
|
@ -8,6 +8,8 @@ dashedName: mutate-an-array-declared-with-const
|
||||
|
||||
# --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.
|
||||
|
||||
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`.
|
||||
|
@ -10,7 +10,7 @@ dashedName: refactor-global-variables-out-of-functions
|
||||
|
||||
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.
|
||||
|
||||
@ -86,7 +86,7 @@ assert(
|
||||
|
||||
```js
|
||||
// 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
|
||||
function add (bookName) {
|
||||
@ -99,7 +99,7 @@ function add (bookName) {
|
||||
|
||||
// Change code below this line
|
||||
function remove (bookName) {
|
||||
var book_index = bookList.indexOf(bookName);
|
||||
const book_index = bookList.indexOf(bookName);
|
||||
if (book_index >= 0) {
|
||||
|
||||
bookList.splice(book_index, 1);
|
||||
@ -109,9 +109,9 @@ function remove (bookName) {
|
||||
}
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var 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 newBookList = add(bookList, 'A Brief History of Time');
|
||||
const newerBookList = remove(bookList, '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);
|
||||
```
|
||||
@ -120,13 +120,13 @@ console.log(bookList);
|
||||
|
||||
```js
|
||||
// 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];
|
||||
}
|
||||
|
||||
function remove (bookList, bookName) {
|
||||
function remove(bookList, bookName) {
|
||||
const bookListCopy = [...bookList];
|
||||
const bookNameIndex = bookList.indexOf(bookName);
|
||||
if (bookNameIndex >= 0) {
|
||||
@ -135,7 +135,7 @@ function remove (bookList, bookName) {
|
||||
return bookListCopy;
|
||||
}
|
||||
|
||||
var newBookList = add(bookList, 'A Brief History of Time');
|
||||
var 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 newBookList = add(bookList, 'A Brief History of Time');
|
||||
const newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
|
||||
const newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
|
||||
```
|
||||
|
@ -55,7 +55,7 @@ Você não deve usar loops `for`.
|
||||
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
|
||||
assert.deepEqual(filteredList, [
|
||||
@ -72,7 +72,7 @@ assert.deepEqual(filteredList, [
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -187,7 +187,7 @@ var watchList = [
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var filteredList;
|
||||
const filteredList = "";
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
@ -197,8 +197,7 @@ console.log(filteredList);
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -311,7 +310,5 @@ var watchList = [
|
||||
}
|
||||
];
|
||||
|
||||
// Only change code below this line
|
||||
let filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
// Only change code above this line
|
||||
const filteredList = watchList.filter(e => e.imdbRating >= 8).map( ({Title: title, imdbRating: rating}) => ({title, rating}) );
|
||||
```
|
||||
|
@ -61,7 +61,7 @@ Você deve usar o método `map`.
|
||||
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
|
||||
assert.deepEqual(ratings, [
|
||||
@ -79,7 +79,7 @@ assert.deepEqual(ratings, [
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -194,9 +194,9 @@ var watchList = [
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
var ratings = [];
|
||||
for(var i=0; i < watchList.length; i++){
|
||||
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
|
||||
const ratings = [];
|
||||
for (let i = 0; i < watchList.length; i++) {
|
||||
ratings.push({title: watchList[i]["Title"], rating: watchList[i]["imdbRating"]});
|
||||
}
|
||||
|
||||
// Only change code above this line
|
||||
@ -207,8 +207,7 @@ console.log(JSON.stringify(ratings));
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// The global variable
|
||||
var watchList = [
|
||||
const watchList = [
|
||||
{
|
||||
"Title": "Inception",
|
||||
"Year": "2010",
|
||||
@ -321,7 +320,7 @@ var watchList = [
|
||||
}
|
||||
];
|
||||
|
||||
var ratings = watchList.map(function(movie) {
|
||||
const ratings = watchList.map(function(movie) {
|
||||
return {
|
||||
title: movie["Title"],
|
||||
rating: movie["imdbRating"]
|
||||
|
Reference in New Issue
Block a user