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,8 +16,9 @@ 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);
} }
``` ```
@ -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,8 +14,9 @@ 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);
} }
``` ```
@ -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,8 +26,9 @@ 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);
} }
``` ```
@ -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,8 +14,9 @@ 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++;
@ -56,16 +57,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 = [];
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");
``` ```
@ -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;
``` ```
@ -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]);
} }
} }
@ -66,7 +67,7 @@ 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
@ -80,14 +81,12 @@ multiplyAll([[1,2],[3,4],[5,6,7]]);
```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

@ -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.
@ -26,6 +26,7 @@ function test (myCondition) {
} }
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,7 +120,7 @@ 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];
@ -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

@ -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

@ -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,8 +194,8 @@ 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"]});
} }
@ -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"]