chore(i18n): download curriculum manually (#42835)
This commit is contained in:
committed by
GitHub
parent
2f8c5619ff
commit
fc0511bd91
@ -11,7 +11,7 @@ dashedName: create-decimal-numbers-with-javascript
|
||||
|
||||
Nós também podemos armazenar números decimais em variáveis. Números decimais são referidos as vezes como números de <dfn>ponto flutuante</dfn> ou <dfn>floats</dfn>.
|
||||
|
||||
**Nota:** Nem todos os números reais podem ser representados com precisão no <dfn>ponto flutuante</dfn>. Isso pode levar a erros de arredondamento. [Detalhes aqui](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
|
||||
**Nota:** Nem todos os números reais podem ser representados com precisão no <dfn>ponto flutuante</dfn>. Isso pode levar a erros de arredondamento. [Detalhes aqui](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems).
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ac
|
||||
title: Increment a Number with JavaScript
|
||||
title: Incremente um Número com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GLT9'
|
||||
forumTopicId: 18201
|
||||
@ -9,33 +9,33 @@ dashedName: increment-a-number-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
You can easily <dfn>increment</dfn> or add one to a variable with the `++` operator.
|
||||
Você pode facilmente <dfn>incrementar</dfn> ou adicionar 1 à variável com o operador `++`.
|
||||
|
||||
```js
|
||||
i++;
|
||||
```
|
||||
|
||||
is the equivalent of
|
||||
é o equivalente a
|
||||
|
||||
```js
|
||||
i = i + 1;
|
||||
```
|
||||
|
||||
**Note:** The entire line becomes `i++;`, eliminating the need for the equal sign.
|
||||
**Nota:** A linha inteira se torna `i++;`, eliminando a necessidade do sinal de igual.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the code to use the `++` operator on `myVar`.
|
||||
Modifique o código usando o operador `++` em `myVar`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar` should equal `88`.
|
||||
`myVar` deve ser igual a `88`.
|
||||
|
||||
```js
|
||||
assert(myVar === 88);
|
||||
```
|
||||
|
||||
You should not use the assignment operator.
|
||||
Você não deve usar o operador de atribuição.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,13 +43,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use the `++` operator.
|
||||
Você deve usar o operador `++`.
|
||||
|
||||
```js
|
||||
assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
|
||||
```
|
||||
|
||||
You should not change code above the specified comment.
|
||||
Você não deve alterar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(/var myVar = 87;/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a9
|
||||
title: Initializing Variables with the Assignment Operator
|
||||
title: Inicializando Variáveis com o Operador de Atribuição
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWJ4Bfb'
|
||||
forumTopicId: 301171
|
||||
@ -9,21 +9,21 @@ dashedName: initializing-variables-with-the-assignment-operator
|
||||
|
||||
# --description--
|
||||
|
||||
It is common to <dfn>initialize</dfn> a variable to an initial value in the same line as it is declared.
|
||||
É comum <dfn>inicializar</dfn> a variável com um valor inicial na mesma linha que declarada.
|
||||
|
||||
```js
|
||||
var myVar = 0;
|
||||
```
|
||||
|
||||
Creates a new variable called `myVar` and assigns it an initial value of `0`.
|
||||
Cria uma nova variável chamada `myVar` e atribui o seu valor inicial como `0`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Define a variable `a` with `var` and initialize it to a value of `9`.
|
||||
Define uma variável `a` com `var` e a inicializa com o valor de `9`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should initialize `a` to a value of `9`.
|
||||
Você deve inicializar `a` para o valor de `9`.
|
||||
|
||||
```js
|
||||
assert(/var\s+a\s*=\s*9(\s*;?\s*)$/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244db
|
||||
title: Introducing Else If Statements
|
||||
title: Introduzindo Instruções Else If
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJ2hm'
|
||||
forumTopicId: 18206
|
||||
@ -9,7 +9,7 @@ dashedName: introducing-else-if-statements
|
||||
|
||||
# --description--
|
||||
|
||||
If you have multiple conditions that need to be addressed, you can chain `if` statements together with `else if` statements.
|
||||
Se você tem múltiplas condições que precisam ser resolvidas, você pode encadear as instruções `if` junto com instruções `else if`.
|
||||
|
||||
```js
|
||||
if (num > 15) {
|
||||
@ -23,23 +23,23 @@ if (num > 15) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the logic to use `else if` statements.
|
||||
Converta a lógica para usar instruções `else if`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should have at least two `else` statements
|
||||
Você deve ter pelo menos duas instruções `else`
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 1);
|
||||
```
|
||||
|
||||
You should have at least two `if` statements
|
||||
Você deve ter pelo menos duas instruções `if`
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 1);
|
||||
```
|
||||
|
||||
You should have closing and opening curly braces for each `if else` code block.
|
||||
Você deve ter chaves de abertura e fechamento para cada bloco de código de `if else`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -49,31 +49,31 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`testElseIf(0)` should return the string `Smaller than 5`
|
||||
`testElseIf(0)` deve retornar a string `Smaller than 5`
|
||||
|
||||
```js
|
||||
assert(testElseIf(0) === 'Smaller than 5');
|
||||
```
|
||||
|
||||
`testElseIf(5)` should return the string `Between 5 and 10`
|
||||
`testElseIf(5)` deve retornar a string `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(5) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(7)` should return the string `Between 5 and 10`
|
||||
`testElseIf(7)` deve retornar a string `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(7) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(10)` should return the string `Between 5 and 10`
|
||||
`testElseIf(10)` deve retornar a string `Between 5 and 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(10) === 'Between 5 and 10');
|
||||
```
|
||||
|
||||
`testElseIf(12)` should return the string `Greater than 10`
|
||||
`testElseIf(12)` deve retornar a string `Greater than 10`
|
||||
|
||||
```js
|
||||
assert(testElseIf(12) === 'Greater than 10');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244da
|
||||
title: Introducing Else Statements
|
||||
title: Introduzindo Instruções Else
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cek4Efq'
|
||||
forumTopicId: 18207
|
||||
@ -9,7 +9,7 @@ dashedName: introducing-else-statements
|
||||
|
||||
# --description--
|
||||
|
||||
When a condition for an `if` statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an `else` statement, an alternate block of code can be executed.
|
||||
Quando uma condição para uma instrução `if` for verdadeiro, o bloco de código seguinte será executado. E quando a condição for falsa? Normalmente nada aconteceria. Com uma instrução `else`, um bloco de código alternativo pode ser executado.
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
@ -21,47 +21,47 @@ if (num > 10) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Combine the `if` statements into a single `if/else` statement.
|
||||
Combine as instruções `if` em uma única instrução `if/else`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should only have one `if` statement in the editor
|
||||
Você deve ter apenas uma instrução `if` no editor
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
You should use an `else` statement
|
||||
Você deve usar uma instrução `else`
|
||||
|
||||
```js
|
||||
assert(/else/g.test(code));
|
||||
```
|
||||
|
||||
`testElse(4)` should return the string `5 or Smaller`
|
||||
`testElse(4)` deve retornar a string `5 or Smaller`
|
||||
|
||||
```js
|
||||
assert(testElse(4) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(5)` should return the string `5 or Smaller`
|
||||
`testElse(5)` deve retornar a string `5 or Smaller`
|
||||
|
||||
```js
|
||||
assert(testElse(5) === '5 or Smaller');
|
||||
```
|
||||
|
||||
`testElse(6)` should return the string `Bigger than 5`
|
||||
`testElse(6)` deve retornar a string `Bigger than 5`
|
||||
|
||||
```js
|
||||
assert(testElse(6) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
`testElse(10)` should return the string `Bigger than 5`
|
||||
`testElse(10)` deve retornar a string `Bigger than 5`
|
||||
|
||||
```js
|
||||
assert(testElse(10) === 'Bigger than 5');
|
||||
```
|
||||
|
||||
You should not change the code above or below the specified comments.
|
||||
Você não deve alterar o código acima ou abaixo dos comentários especificados.
|
||||
|
||||
```js
|
||||
assert(/var result = "";/.test(code) && /return result;/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56104e9e514f539506016a5c
|
||||
title: Iterate Odd Numbers With a For Loop
|
||||
title: Itere Números Ímpares Com um Laço For
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm8n7T9'
|
||||
forumTopicId: 18212
|
||||
@ -9,9 +9,9 @@ dashedName: iterate-odd-numbers-with-a-for-loop
|
||||
|
||||
# --description--
|
||||
|
||||
For loops don't have to iterate one at a time. By changing our `final-expression`, we can count by even numbers.
|
||||
Laços for não tem de iterar um de cada vez. Ao alterar nossa `expressão final`, nós podemos contar os números pares.
|
||||
|
||||
We'll start at `i = 0` and loop while `i < 10`. We'll increment `i` by 2 each loop with `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
|
||||
var ourArray = [];
|
||||
@ -20,21 +20,21 @@ for (var i = 0; i < 10; i += 2) {
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` will now contain `[0,2,4,6,8]`. Let's change our `initialization` so we can count by odd numbers.
|
||||
`ourArray` agora conterá `[0,2,4,6,8]`. Vamos mudar nossa `inicialização` para que possamos contar por números ímpares.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Push the odd numbers from 1 through 9 to `myArray` using a `for` loop.
|
||||
Adicione (push) os números ímpares de 9 até 1 para `myArray` usando um laço `for`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `for` loop for this.
|
||||
Você deve estar usando um laço `for` para isso.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` should equal `[1,3,5,7,9]`.
|
||||
`myArray` deve ser igual a `[1,3,5,7,9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5675e877dbd60be8ad28edc6
|
||||
title: Iterate Through an Array with a For Loop
|
||||
title: Itere através de um Array com Laço For
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeR3HB'
|
||||
forumTopicId: 18216
|
||||
@ -9,7 +9,7 @@ dashedName: iterate-through-an-array-with-a-for-loop
|
||||
|
||||
# --description--
|
||||
|
||||
A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a `for` loop. This code will output each element of the array `arr` to the console:
|
||||
Uma tarefa comum em JavaScript é para iterar através do conteúdo de um array. Uma forma de fazer isso é com um laço `for`. Esse código irá exibir cada elemento do array `arr` no console:
|
||||
|
||||
```js
|
||||
var arr = [10, 9, 8, 7, 6];
|
||||
@ -18,33 +18,33 @@ for (var i = 0; i < arr.length; i++) {
|
||||
}
|
||||
```
|
||||
|
||||
Remember that arrays have zero-based indexing, which means the last index of the array is `length - 1`. Our condition for this loop is `i < arr.length`, which stops the loop when `i` is equal to `length`. In this case the last iteration is `i === 4` i.e. when `i` becomes equal to `arr.length - 1` and outputs `6` to the console. Then `i` increases to `5`, and the loop terminates because `i < arr.length` is `false`.
|
||||
Lembre-se de que arrays têm indexação baseada em zero, o que significa que o último índice do array é de `length - 1`. Nossa condição para esse laço é `i < arr.length`, a qual interrompe o laço quando `i` é igual a `length`. Nesse caso a última iteração é ` i === 4` i.e. quando `i` se tornar igual a `arr.length - 1` e exibe `6` no console. Em seguida, `i` aumenta para `5`, e o laço é interrompido porque `i < arr.length` é `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Declare and initialize a variable `total` to `0`. Use a `for` loop to add the value of each element of the `myArr` array to `total`.
|
||||
Declare e inicialize uma variável `total` como `0`. Use um laço `for` para adicionar o valor de cada elemento do array `myArr` para `total`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`total` should be declared and initialized to 0.
|
||||
`total` deve ser declarado e inicializado como 0.
|
||||
|
||||
```js
|
||||
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
|
||||
```
|
||||
|
||||
`total` should equal 20.
|
||||
`total` deve ser igual a 20.
|
||||
|
||||
```js
|
||||
assert(total === 20);
|
||||
```
|
||||
|
||||
You should use a `for` loop to iterate through `myArr`.
|
||||
Você deve usar um laço `for` para iterar através de `myArr`.
|
||||
|
||||
```js
|
||||
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
|
||||
```
|
||||
|
||||
You should not attempt to directly assign the value 20 to `total`.
|
||||
Você não deve tentar atribuir diretamente o valor 20 para `total`.
|
||||
|
||||
```js
|
||||
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a2efd662fb457916e1fe604
|
||||
title: Iterate with JavaScript Do...While Loops
|
||||
title: Itere com Laços Do...While JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqWGcp'
|
||||
forumTopicId: 301172
|
||||
@ -9,7 +9,7 @@ dashedName: iterate-with-javascript-do---while-loops
|
||||
|
||||
# --description--
|
||||
|
||||
The next type of loop you will learn is called a `do...while` loop. It is called a `do...while` loop because it will first `do` one pass of the code inside the loop no matter what, and then continue to run the loop `while` the specified condition evaluates to `true`.
|
||||
O próximo tipo de laço que você aprenderá é chamado de laço `do...while`. É chamado um laço `do...while` porque primeiro irá toda vez `fazer (do)`, ou executar, uma vez o bloco de código após a instrução do, não importa o que acontecer, e então continuará a executar o laço `enquanto (while)` a condição for `true`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -20,7 +20,7 @@ do {
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
The example above behaves similar to other types of loops, and the resulting array will look like `[0, 1, 2, 3, 4]`. However, what makes the `do...while` different from other loops is how it behaves when the condition fails on the first check. Let's see this in action: Here is a regular `while` loop that will run the code in the loop as long as `i < 5`:
|
||||
O exemplo acima se comporta de forma similar a outros tipos de laços, e o array resultante se parecerá com `[0,1,2,3,4]`. No entanto, o que torna o laço `do...while` diferente de outros laços é como ele se comporta quando uma condição falha na primeira verificação. Vamos ver isso na prática: Aqui está um laço comum `while` que rodará o código no laço enquanto `i < 5`:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -31,7 +31,7 @@ while (i < 5) {
|
||||
}
|
||||
```
|
||||
|
||||
In this example, we initialize the value of `ourArray` to an empty array and the value of `i` to 5. When we execute the `while` loop, the condition evaluates to `false` because `i` is not less than 5, so we do not execute the code inside the loop. The result is that `ourArray` will end up with no values added to it, and it will still look like `[]` when all of the code in the example above has completed running. Now, take a look at a `do...while` loop:
|
||||
Nesse exemplo, inicializamos o valor de `ourArray` como um array vazio e o valor de `i` sendo 5. Quando executamos o laço `while`, a condição é igual a `false` porque `i` não é menor que 5, portanto nós não executamos o código dentro do laço. O resultado é que `ourArray` terminará sem valores adicionados a ele, e ainda se parecerá com `[]` quando todas as linhas do código no exemplo acima for completamente executadas. Agora, dê uma olhada no laço `do...while`:
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -42,27 +42,27 @@ do {
|
||||
} while (i < 5);
|
||||
```
|
||||
|
||||
In this case, we initialize the value of `i` to 5, just like we did with the `while` loop. When we get to the next line, there is no condition to evaluate, so we go to the code inside the curly braces and execute it. We will add a single element to the array and then increment `i` before we get to the condition check. When we finally evaluate the condition `i < 5` on the last line, we see that `i` is now 6, which fails the conditional check, so we exit the loop and are done. At the end of the above example, the value of `ourArray` is `[5]`. Essentially, a `do...while` loop ensures that the code inside the loop will run at least once. Let's try getting a `do...while` loop to work by pushing values to an array.
|
||||
Nesse caso, nós inicializamos o valor de `i` para 5, assim como fizemos com o laço `while`. Quando chegamos na próxima linha, não há condição a ser analisada, então nós vamos ao código dentro das chaves e o executamos. Nós adicionaremos um único elemento ao array e então incrementamos `i` antes de chegarmos a verificação da condição. Quando nós finalmente temos o resultado da condição `i < 5` na última linha, nós notamos que `i` agora é 6, o que não cumpre a verificação da condição, então nós saímos do laço e terminamos. Ao final do exemplo acima, o valor de `ourArray` é `[5]`. Essencialmente, um laço `do...while` garante que o código dentro do laço será executado pelo menos uma vez. Vamos tentar fazer um laço `do...while` funcionar empurrando valores para um array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `while` loop in the code to a `do...while` loop so the loop will push only the number `10` to `myArray`, and `i` will be equal to `11` when your code has finished running.
|
||||
Altere o laço `while` no código para um laço `do...while` para que o laço adicione apenas o número `10` no `myArray` e `i` será igual a `11` quando seu código terminar de rodar.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `do...while` loop for this exercise.
|
||||
Você deve usar um laço `do...while` nesse exercício.
|
||||
|
||||
```js
|
||||
assert(code.match(/do/g));
|
||||
```
|
||||
|
||||
`myArray` should equal `[10]`.
|
||||
`myArray` deve ser igual a `[10]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [10]);
|
||||
```
|
||||
|
||||
`i` should equal `11`
|
||||
`i` deve ser igual a `11`
|
||||
|
||||
```js
|
||||
assert.equal(i, 11);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb5bdef
|
||||
title: Iterate with JavaScript For Loops
|
||||
title: Itere com Laços For JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yNVCe'
|
||||
forumTopicId: 18219
|
||||
@ -9,21 +9,21 @@ dashedName: iterate-with-javascript-for-loops
|
||||
|
||||
# --description--
|
||||
|
||||
You can run the same code multiple times by using a loop.
|
||||
Você pode rodar o mesmo código várias vezes usando um laço.
|
||||
|
||||
The most common type of JavaScript loop is called a `for` loop because it runs for a specific number of times.
|
||||
O tipo mais comum de laço JavaScript é chamado de laço `for` porque ele é executado por um número especificado de vezes.
|
||||
|
||||
For loops are declared with three optional expressions separated by semicolons:
|
||||
Laços For são declarados com três expressões opcionais separadas por ponto e vírgula:
|
||||
|
||||
`for (a; b; c)`, where `a` is the intialization statement, `b` is the condition statement, and `c` is the final expression.
|
||||
`for (a; b; c)`, onde `a` é a declaração de inicialização, `b` é a declaração de condição, e `c` é a expressão final.
|
||||
|
||||
The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.
|
||||
A declaração de inicialização é executada apenas uma vez antes do laço iniciar. Normalmente é usado para definir e configurar sua variável de laço.
|
||||
|
||||
The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to `true`. When the condition is `false` at the start of the iteration, the loop will stop executing. This means if the condition starts as false, your loop will never execute.
|
||||
A declaração de condição é verificada no início de cada iteração do laço e irá continuar enquanto seu valor for `true`. Quando a condição for `false` no início da iteração, o laço irá parar de executar. Isso significa que se a condição de início for falsa, seu laço nunca será executado.
|
||||
|
||||
The final expression is executed at the end of each loop iteration, prior to the next condition check and is usually used to increment or decrement your loop counter.
|
||||
A expressão final é executada no final de cada iteração do laço, antes da verificação da próxima condição e normalmente é usada para incrementar ou decrementar o contador do laço.
|
||||
|
||||
In the following example we initialize with `i = 0` and iterate while our condition `i < 5` is true. We'll increment `i` by `1` in each loop iteration with `i++` as our final expression.
|
||||
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 = [];
|
||||
@ -32,21 +32,21 @@ for (var i = 0; i < 5; i++) {
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` will now have the value `[0,1,2,3,4]`.
|
||||
`ourArray` agora terá o valor de `[0,1,2,3,4]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use a `for` loop to push the values 1 through 5 onto `myArray`.
|
||||
Use o laço `for` para adicionar os valores de 1 até 5 dentro de `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `for` loop for this.
|
||||
Você deve usar um laço `for` para isso.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
`myArray` should equal `[1,2,3,4,5]`.
|
||||
`myArray` deve ser igual a `[1,2,3,4,5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb1bdef
|
||||
title: Iterate with JavaScript While Loops
|
||||
title: Itere com Laços While em JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c8QbnCM'
|
||||
forumTopicId: 18220
|
||||
@ -9,9 +9,9 @@ dashedName: iterate-with-javascript-while-loops
|
||||
|
||||
# --description--
|
||||
|
||||
You can run the same code multiple times by using a loop.
|
||||
Você pode rodar o mesmo código várias vezes ao usar um laço.
|
||||
|
||||
The first type of loop we will learn is called a `while` loop because it runs while a specified condition is true and stops once that condition is no longer true.
|
||||
O primeiro tipo de laço que aprenderemos é chamado de laço `while` porque ele irá rodar enquanto uma condição específica for verdadeira e irá parar uma vez que a condição não for mais verdadeira.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -22,23 +22,23 @@ while(i < 5) {
|
||||
}
|
||||
```
|
||||
|
||||
In the code example above, the `while` loop will execute 5 times and append the numbers 0 through 4 to `ourArray`.
|
||||
No código de exemplo acima, o laço `while` executará por 5 vezes e adicionará os números de 0 até 4 ao `ourArray`.
|
||||
|
||||
Let's try getting a while loop to work by pushing values to an array.
|
||||
Vamos tentar fazer um laço while funcionar empurrando valores para um array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the numbers 5 through 0 (inclusive) in descending order to `myArray` using a `while` loop.
|
||||
Adicione os números de 5 até 1 (inclusivo) em ordem descendente para `myArray` usando um laço `while`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `while` loop for this.
|
||||
Você deve usar um laço `while` para isso.
|
||||
|
||||
```js
|
||||
assert(code.match(/while/g));
|
||||
```
|
||||
|
||||
`myArray` should equal `[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]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bf
|
||||
title: Local Scope and Functions
|
||||
title: Escopo Local e Funções
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cd62NhM'
|
||||
forumTopicId: 18227
|
||||
@ -9,9 +9,9 @@ dashedName: local-scope-and-functions
|
||||
|
||||
# --description--
|
||||
|
||||
Variables which are declared within a function, as well as the function parameters, have <dfn>local</dfn> scope. That means they are only visible within that function.
|
||||
Variáveis que são declaradas dentro de uma função, assim como parâmetros de funções, possuem escopo <dfn>local</dfn>. Isso significa que eles são visíveis apenas dentro da função.
|
||||
|
||||
Here is a function `myTest` with a local variable called `loc`.
|
||||
Aqui está uma função `myTest` com uma variável local chamada `loc`.
|
||||
|
||||
```js
|
||||
function myTest() {
|
||||
@ -22,17 +22,17 @@ myTest();
|
||||
console.log(loc);
|
||||
```
|
||||
|
||||
The `myTest()` function call will display the string `foo` in the console. The `console.log(loc)` line will throw an error, as `loc` is not defined outside of the function.
|
||||
A chamada da função `myTest()` irá exibir a string `foo` no console. A linha `console.log(loc)` irá lançar um erro, já que `loc` não foi definido fora da função.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The editor has two `console.log`s to help you see what is happening. Check the console as you code to see how it changes. Declare a local variable `myVar` inside `myLocalScope` and run the tests.
|
||||
O editor possui dois `console.log` para te ajudar a ver o que está acontecendo. Verifique o console enquanto codifica para ver como muda. Declare uma variável local `myVar` dentro de `myLocalScope` e rode os testes.
|
||||
|
||||
**Note:** The console will still display `ReferenceError: myVar is not defined`, but this will not cause the tests to fail.
|
||||
**Nota:** O console ainda exibirá `ReferenceError: myVar is not defined`, mas isso não causará falha nos testes.
|
||||
|
||||
# --hints--
|
||||
|
||||
The code should not contain a global `myVar` variable.
|
||||
O código não deve conter uma variável global `myVar`.
|
||||
|
||||
```js
|
||||
function declared() {
|
||||
@ -41,7 +41,7 @@ function declared() {
|
||||
assert.throws(declared, ReferenceError);
|
||||
```
|
||||
|
||||
You should add a local `myVar` variable.
|
||||
Você deve adicionar a variável local `myVar`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5690307fddb111c6084545d7
|
||||
title: Logical Order in If Else Statements
|
||||
title: Ordem Lógica em Instruções If Else
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cwNvMUV'
|
||||
forumTopicId: 18228
|
||||
@ -9,13 +9,13 @@ dashedName: logical-order-in-if-else-statements
|
||||
|
||||
# --description--
|
||||
|
||||
Order is important in `if`, `else if` statements.
|
||||
Ordem é importante em instruções `if` e `else if`.
|
||||
|
||||
The function is executed from top to bottom so you will want to be careful of what statement comes first.
|
||||
A função é executada de cima para baixo, então você deve ser cuidados com qual instrução vem primeiro.
|
||||
|
||||
Take these two functions as an example.
|
||||
Tomem essas duas funções como exemplo.
|
||||
|
||||
Here's the first:
|
||||
Aqui está a primeira:
|
||||
|
||||
```js
|
||||
function foo(x) {
|
||||
@ -29,7 +29,7 @@ function foo(x) {
|
||||
}
|
||||
```
|
||||
|
||||
And the second just switches the order of the statements:
|
||||
E a segunda apenas altera a ordem das instruções if e else if:
|
||||
|
||||
```js
|
||||
function bar(x) {
|
||||
@ -43,34 +43,34 @@ function bar(x) {
|
||||
}
|
||||
```
|
||||
|
||||
While these two functions look nearly identical if we pass a number to both we get different outputs.
|
||||
Embora as duas funções se pareçam praticamente idênticas, se nós passarmos um número para ambos nós teremos saídas diferentes.
|
||||
|
||||
```js
|
||||
foo(0)
|
||||
bar(0)
|
||||
```
|
||||
|
||||
`foo(0)` will return the string `Less than one`, and `bar(0)` will return the string `Less than two`.
|
||||
`foo(0)` retornará a string `Less than one`, e `bar(0)` retornará a string `Less than two`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the order of logic in the function so that it will return the correct statements in all cases.
|
||||
Altere a ordem lógica na função para que retorne as instruções corretas em todos os cenários.
|
||||
|
||||
# --hints--
|
||||
|
||||
`orderMyLogic(4)` should return the string `Less than 5`
|
||||
`orderMyLogic(4)` deve retornar a string `Less than 5`
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(4) === 'Less than 5');
|
||||
```
|
||||
|
||||
`orderMyLogic(6)` should return the string `Less than 10`
|
||||
`orderMyLogic(6)` deve retornar a string `Less than 10`
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(6) === 'Less than 10');
|
||||
```
|
||||
|
||||
`orderMyLogic(11)` should return the string `Greater than or equal to 10`
|
||||
`orderMyLogic(11)` deve retornar a string `Greater than or equal to 10`
|
||||
|
||||
```js
|
||||
assert(orderMyLogic(11) === 'Greater than or equal to 10');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cc
|
||||
title: Manipulate Arrays With pop()
|
||||
title: Manipule Arrays com pop()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRbVZAB'
|
||||
forumTopicId: 18236
|
||||
@ -9,11 +9,11 @@ dashedName: manipulate-arrays-with-pop
|
||||
|
||||
# --description--
|
||||
|
||||
Another way to change the data in an array is with the `.pop()` function.
|
||||
Outra forma de alterar os dados em um array é com a função `.pop()`.
|
||||
|
||||
`.pop()` is used to pop a value off of the end of an array. We can store this popped off value by assigning it to a variable. In other words, `.pop()` removes the last element from an array and returns that element.
|
||||
`.pop()` é usado para remover um valor do final do array. Nós podemos armazenar esse valor removido ao atribuir a saída da chamada do método a uma variável. Em outras palavras, `.pop()` remove o último elemento de um array e retorna aquele elemento.
|
||||
|
||||
Any type of entry can be popped off of an array - numbers, strings, even nested arrays.
|
||||
Qualquer tipo de entrada pode ser removida de um array - numbers, strings e até mesmo arrays aninhados.
|
||||
|
||||
```js
|
||||
var threeArr = [1, 4, 6];
|
||||
@ -22,15 +22,15 @@ console.log(oneDown);
|
||||
console.log(threeArr);
|
||||
```
|
||||
|
||||
The first `console.log` will display the value `6`, and the second will display the value `[1, 4]`.
|
||||
O primeiro `consol.log` exibirá o valor `6`, e o segundo irá exibir o valor `[1, 4]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `.pop()` function to remove the last item from `myArray`, assigning the popped off value to `removedFromMyArray`.
|
||||
Use a função `.pop()` para remover o último item de `myArray`, atribuindo o valor removido para `removedFromMyArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should only contain `[["John", 23]]`.
|
||||
`myArray` deve conter apenas `[["John", 23]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -44,13 +44,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use `pop()` on `myArray`.
|
||||
Você deve usar `pop()` em `myArray`.
|
||||
|
||||
```js
|
||||
assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
|
||||
```
|
||||
|
||||
`removedFromMyArray` should only contain `["cat", 2]`.
|
||||
`removedFromMyArray` deve conter apenas `["cat", 2]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cb
|
||||
title: Manipulate Arrays With push()
|
||||
title: Manipule Arrays Com push()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cnqmVtJ'
|
||||
forumTopicId: 18237
|
||||
@ -9,11 +9,11 @@ dashedName: manipulate-arrays-with-push
|
||||
|
||||
# --description--
|
||||
|
||||
An easy way to append data to the end of an array is via the `push()` function.
|
||||
Uma forma fácil de adicionar dados no final de um array é através da função `push()`.
|
||||
|
||||
`.push()` takes one or more <dfn>parameters</dfn> and "pushes" them onto the end of the array.
|
||||
`.push()` recebe um ou mais <dfn>parâmetros</dfn> e "empurra" eles no final do array.
|
||||
|
||||
Examples:
|
||||
Exemplos:
|
||||
|
||||
```js
|
||||
var arr1 = [1,2,3];
|
||||
@ -23,15 +23,15 @@ var arr2 = ["Stimpson", "J", "cat"];
|
||||
arr2.push(["happy", "joy"]);
|
||||
```
|
||||
|
||||
`arr1` now has the value `[1, 2, 3, 4]` and `arr2` has the value `["Stimpson", "J", "cat", ["happy", "joy"]]`.
|
||||
`arr1` agora tem o valor de `[1, 2, 3, 4]` e `arr2` tem o valor de `["Stimpson", "J", "cat", ["happy", "joy"]]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Push `["dog", 3]` onto the end of the `myArray` variable.
|
||||
Empurre `["dog", 3]` no final da variável `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should now equal `[["John", 23], ["cat", 2], ["dog", 3]]`.
|
||||
`myArray` agora deve ser igual a `[["John", 23], ["cat", 2], ["dog", 3]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cd
|
||||
title: Manipulate Arrays With shift()
|
||||
title: Manipule Arrays Com shift()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRbVETW'
|
||||
forumTopicId: 18238
|
||||
@ -9,26 +9,26 @@ dashedName: manipulate-arrays-with-shift
|
||||
|
||||
# --description--
|
||||
|
||||
`pop()` always removes the last element of an array. What if you want to remove the first?
|
||||
`pop()` sempre remove o último elemento de um array. E se você quiser remover o primeiro?
|
||||
|
||||
That's where `.shift()` comes in. It works just like `.pop()`, except it removes the first element instead of the last.
|
||||
É aí que o `.shift()` vem a ser útil. Ele funciona da mesma forma que `.pop()`, exceto que ele remove o primeiro elemento ao invés do último.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", ["cat"]];
|
||||
var removedFromOurArray = ourArray.shift();
|
||||
```
|
||||
|
||||
`removedFromOurArray` would have a value of the string `Stimpson`, and `ourArray` would have `["J", ["cat"]]`.
|
||||
`removedFromOurArray` teria o valor da string `Stimpson` e `ourArray` teria o valor de `["J", ["cat"]]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `.shift()` function to remove the first item from `myArray`, assigning the "shifted off" value to `removedFromMyArray`.
|
||||
Use a função `.shift()` para remover o primeiro item de `myArray`, atribuindo o valor "removido" para `removedFromMyArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should now equal `[["dog", 3]]`.
|
||||
`myArray` agora deve ser igual a `[["dog", 3]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`removedFromMyArray` should contain `["John", 23]`.
|
||||
`removedFromMyArray` deve conter `["John", 23]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ce
|
||||
title: Manipulate Arrays With unshift()
|
||||
title: Manipule Arrays Com unshift()
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ckNDESv'
|
||||
forumTopicId: 18239
|
||||
@ -9,11 +9,11 @@ dashedName: manipulate-arrays-with-unshift
|
||||
|
||||
# --description--
|
||||
|
||||
Not only can you `shift` elements off of the beginning of an array, you can also `unshift` elements to the beginning of an array i.e. add elements in front of the array.
|
||||
Não só você pode `remover` elementos do início de um array, como você também pode `adicionar (unshift)` elementos ao início de um array i.e. adiciona elementos na frente do array.
|
||||
|
||||
`.unshift()` works exactly like `.push()`, but instead of adding the element at the end of the array, `unshift()` adds the element at the beginning of the array.
|
||||
`.unshift()` funciona exatamente como `.push()`, mas ao invés de adicionar o elemento ao final do array, `unshift` adiciona o elemento no início do array.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourArray = ["Stimpson", "J", "cat"];
|
||||
@ -21,15 +21,15 @@ ourArray.shift();
|
||||
ourArray.unshift("Happy");
|
||||
```
|
||||
|
||||
After the `shift`, `ourArray` would have the value `["J", "cat"]`. After the `unshift`, `ourArray` would have the value `["Happy", "J", "cat"]`.
|
||||
Após o `shift`, `ourArray` teria o valor `["J","cat"]`. Após o `unshift`, `ourArray` teria o valor `["Happy","J","cat"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add `["Paul",35]` to the beginning of the `myArray` variable using `unshift()`.
|
||||
Adicione `["Paul",35]` ao início da variável `myArray` usando `unshift()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should now have `[["Paul", 35], ["dog", 3]]`.
|
||||
`myArray` agora deve ter `[["Paul", 35], ["dog", 3]]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cb
|
||||
title: Manipulating Complex Objects
|
||||
title: Manipulando Objetos Complexos
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yNMfR'
|
||||
forumTopicId: 18208
|
||||
@ -9,9 +9,9 @@ dashedName: manipulating-complex-objects
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you may want to store data in a flexible <dfn>Data Structure</dfn>. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, <dfn>functions</dfn>, and <dfn>objects</dfn>.
|
||||
Às vezes você pode querer armazenar dados em uma <dfn>Estrutura de Dados</dfn> flexível. Um objeto JavaScript é uma forma de lidar com dados flexíveis. Eles permitem combinações arbitrárias de <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, <dfn>functions</dfn> e <dfn>objects</dfn>.
|
||||
|
||||
Here's an example of a complex data structure:
|
||||
Aqui está um exemplo de estrutura de dados complexas:
|
||||
|
||||
```js
|
||||
var ourMusic = [
|
||||
@ -29,7 +29,7 @@ var ourMusic = [
|
||||
];
|
||||
```
|
||||
|
||||
This is an array which contains one object inside. The object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested `formats` array. If you want to add more album records, you can do this by adding records to the top level array. Objects hold data in a property, which has a key-value format. In the example above, `"artist": "Daft Punk"` is a property that has a key of `artist` and a value of `Daft Punk`. [JavaScript Object Notation](http://www.json.org/) or `JSON` is a related data interchange format used to store data.
|
||||
Isto é um array o qual contém um objeto dentro dele. O objeto possui vários pedaços de <dfn>metadados</dfn> sobre um album. Também possui um array aninhado `formats`. Se você quiser adicionar mais discos de album, você pode fazer isso ao adicionar os discos no array de alto nível. Objetos armazenam dados em uma propriedade, a qual possui um formato de chave-valor. No exemplo acima, `"artist": "Daft Punk"` é uma propriedade que tem uma chave `artist` e um valor de `Daft Punk`. [Notação de Objeto JavaScript](http://www.json.org/) ou `JSON` é um formato, de interalteração de dados relacionados, usado para armazenar dados.
|
||||
|
||||
```json
|
||||
{
|
||||
@ -45,39 +45,39 @@ This is an array which contains one object inside. The object has various pieces
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** You will need to place a comma after every object in the array, unless it is the last object in the array.
|
||||
**Nota:** Você precisará colocar uma vírgula após cada objeto no array, a não ser que for o último objeto no array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a new album to the `myMusic` array. Add `artist` and `title` strings, `release_year` number, and a `formats` array of strings.
|
||||
Adicione um novo álbum para o array `myMusic`. Adicione strings: `artist` e `title`, número: `release_year`, e um array de strings: `formats`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myMusic` should be an array
|
||||
`myMusic` deve ser um array
|
||||
|
||||
```js
|
||||
assert(Array.isArray(myMusic));
|
||||
```
|
||||
|
||||
`myMusic` should have at least two elements
|
||||
`myMusic` deve ter pelo menos dois elementos
|
||||
|
||||
```js
|
||||
assert(myMusic.length > 1);
|
||||
```
|
||||
|
||||
The elements in the `myMusic` array should be objects
|
||||
Os elementos no array `myMusic` devem ser objetos
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {assert.typeOf(object, 'object')})
|
||||
```
|
||||
|
||||
Your object in `myMusic` should have at least 4 properties
|
||||
Seu objeto em `myMusic` deve ter pelo menos 4 propriedades
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {assert(Object.keys(object).length > 3); });
|
||||
```
|
||||
|
||||
Your object in `myMusic` should contain the property `artist` which is a string
|
||||
Seu objeto em `myMusic` deve conter a propriedade `artist` a qual é uma string
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
@ -86,7 +86,7 @@ myMusic.forEach(object => {
|
||||
})
|
||||
```
|
||||
|
||||
Your object in `myMusic` should contain the property `title` which is a string
|
||||
Seu objeto em `myMusic` deve conter a propriedade `title` a qual é uma string
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
@ -95,7 +95,7 @@ myMusic.forEach(object => {
|
||||
})
|
||||
```
|
||||
|
||||
Your object in `myMusic` should contain the property `release_year` which is a number
|
||||
Seu objeto em `myMusic` deve conter a propriedade `release_year` a qual é um número
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
@ -104,7 +104,7 @@ myMusic.forEach(object => {
|
||||
})
|
||||
```
|
||||
|
||||
Your object in `myMusic` should contain a `formats` property which is an array
|
||||
Seu objeto em `myMusic` deve conter a propriedade `formats` a qual é um array
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
@ -113,7 +113,7 @@ myMusic.forEach(object => {
|
||||
})
|
||||
```
|
||||
|
||||
`formats` should be an array of strings with at least two elements
|
||||
`formats` deve ser um array de strings com pelo menos dois elementos
|
||||
|
||||
```js
|
||||
myMusic.forEach(object => {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb8bdef
|
||||
title: Modify Array Data With Indexes
|
||||
title: Modifique Dados de Array Com Índices
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/czQM4A8'
|
||||
forumTopicId: 18241
|
||||
@ -9,26 +9,26 @@ dashedName: modify-array-data-with-indexes
|
||||
|
||||
# --description--
|
||||
|
||||
Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely.
|
||||
Diferente de strings, as entradas de um array são <dfn>mutáveis</dfn> e pode ser modificadas livremente.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
var ourArray = [50,40,30];
|
||||
ourArray[0] = 15;
|
||||
```
|
||||
|
||||
`ourArray` now has the value `[15, 40, 30]`.
|
||||
`ourArray` agora tem o valor `[15, 40, 30]`.
|
||||
|
||||
**Note:** There shouldn't be any spaces between the array name and the square brackets, like `array [0]`. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
|
||||
**Nota:** Não deve ter espaços entre o nome do array e os colchetes, como `array [0]`. Embora JavaScript é capaz de processar isso corretamente, isso pode causar confusão em outros programadores lendo o seu código.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the data stored at index `0` of `myArray` to a value of `45`.
|
||||
Modifique o dado armazenado no índice `0` de `myArray` para um valor de `45`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should now be `[45,64,99]`.
|
||||
`myArray` agora deve ser `[45,64,99]`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -47,7 +47,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should be using correct index to modify the value in `myArray`.
|
||||
Você deve usar o índice correto para modificar o valor em `myArray`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244df
|
||||
title: Multiple Identical Options in Switch Statements
|
||||
title: Várias Opções Idênticas em Instruções Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBKWCV'
|
||||
forumTopicId: 18242
|
||||
@ -9,7 +9,7 @@ dashedName: multiple-identical-options-in-switch-statements
|
||||
|
||||
# --description--
|
||||
|
||||
If the `break` statement is omitted from a `switch` statement's `case`, the following `case` statement(s) are executed until a `break` is encountered. If you have multiple inputs with the same output, you can represent them in a `switch` statement like this:
|
||||
Se a instrução `break` for omitida de uma instrução `case` de um `switch`, as instruções seguintes `case` são executadas até que seja encontrado um `break`. Se você tem várias entradas com a mesma saída, você pode representá-los em uma instrução `switch` da seguinte forma:
|
||||
|
||||
```js
|
||||
var result = "";
|
||||
@ -24,80 +24,80 @@ switch(val) {
|
||||
}
|
||||
```
|
||||
|
||||
Cases for 1, 2, and 3 will all produce the same result.
|
||||
Todos os casos para 1, 2 e 3 irão produzir o mesmo resultado.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a switch statement to set `answer` for the following ranges:
|
||||
Escreva uma instrução para definir `answer` para os seguintes intervalos:
|
||||
`1-3` - `Low`
|
||||
`4-6` - `Mid`
|
||||
`7-9` - `High`
|
||||
|
||||
**Note:** You will need to have a `case` statement for each number in the range.
|
||||
**Nota:** Você precisará ter uma instrução `case` para cada número no intervalo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sequentialSizes(1)` should return the string `Low`
|
||||
`sequentialSizes(1)` deve retornar a string `Low`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(1) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(2)` should return the string `Low`
|
||||
`sequentialSizes(2)` deve retornar a string `Low`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(2) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(3)` should return the string `Low`
|
||||
`sequentialSizes(3)` deve retornar a string `Low`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(3) === 'Low');
|
||||
```
|
||||
|
||||
`sequentialSizes(4)` should return the string `Mid`
|
||||
`sequentialSizes(4)` deve retornar a string `Mid`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(4) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(5)` should return the string `Mid`
|
||||
`sequentialSizes(5)` deve retornar a string `Mid`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(5) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(6)` should return the string `Mid`
|
||||
`sequentialSizes(6)` deve retornar a string `Mid`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(6) === 'Mid');
|
||||
```
|
||||
|
||||
`sequentialSizes(7)` should return the string `High`
|
||||
`sequentialSizes(7)` deve retornar a string `High`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(7) === 'High');
|
||||
```
|
||||
|
||||
`sequentialSizes(8)` should return the string `High`
|
||||
`sequentialSizes(8)` deve retornar a string `High`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(8) === 'High');
|
||||
```
|
||||
|
||||
`sequentialSizes(9)` should return the string `High`
|
||||
`sequentialSizes(9)` deve retornar a string `High`
|
||||
|
||||
```js
|
||||
assert(sequentialSizes(9) === 'High');
|
||||
```
|
||||
|
||||
You should not use any `if` or `else` statements
|
||||
Você não deve usar nenhuma das instruções `if` ou `else`
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
You should have nine `case` statements
|
||||
Você deve ter nove instruções `case`
|
||||
|
||||
```js
|
||||
assert(code.match(/case/g).length === 9);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7993c9c69feddfaeb7bdef
|
||||
title: Multiply Two Decimals with JavaScript
|
||||
title: Multiplique Dois Decimais com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2GeHq'
|
||||
forumTopicId: 301173
|
||||
@ -9,23 +9,23 @@ dashedName: multiply-two-decimals-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, you can also perform calculations with decimal numbers, just like whole numbers.
|
||||
Em JavaScript, você também pode realizar cálculos com números decimais, assim como com números inteiros.
|
||||
|
||||
Let's multiply two decimals together to get their product.
|
||||
Vamos multiplicar dois decimais juntos para obter o produto deles.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0.0` so that product will equal `5.0`.
|
||||
Altere o `0.0` para que o produto seja igual a `5.0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `product` should equal `5.0`.
|
||||
A variável `product` deve ser igual `5.0`.
|
||||
|
||||
```js
|
||||
assert(product === 5.0);
|
||||
```
|
||||
|
||||
You should use the `*` operator
|
||||
Você deve usar o operador `*`
|
||||
|
||||
```js
|
||||
assert(/\*/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1231c1c11feddfaeb5bdef
|
||||
title: Multiply Two Numbers with JavaScript
|
||||
title: Multiplique Dois Números com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cP3y3Aq'
|
||||
forumTopicId: 18243
|
||||
@ -9,31 +9,31 @@ dashedName: multiply-two-numbers-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
We can also multiply one number by another.
|
||||
Nós também podemos multiplicar um número por outro.
|
||||
|
||||
JavaScript uses the `*` symbol for multiplication of two numbers.
|
||||
JavaScript usa o símbolo `*` para multiplicação de dois números.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
myVar = 13 * 13;
|
||||
```
|
||||
|
||||
`myVar` would have the value `169`.
|
||||
`myVar` teria o valor `169`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0` so that product will equal `80`.
|
||||
Altere o `0` para que o produto seja igual a `80`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `product` should be equal to 80.
|
||||
A variável `product` deve ser igual a 80.
|
||||
|
||||
```js
|
||||
assert(product === 80);
|
||||
```
|
||||
|
||||
You should use the `*` operator.
|
||||
Você deve usar o operador `*`.
|
||||
|
||||
```js
|
||||
assert(/\*/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb7bdef
|
||||
title: Nest one Array within Another Array
|
||||
title: Aninhe um Array com Outro Array
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/crZQZf8'
|
||||
forumTopicId: 18247
|
||||
@ -9,21 +9,21 @@ dashedName: nest-one-array-within-another-array
|
||||
|
||||
# --description--
|
||||
|
||||
You can also nest arrays within other arrays, like below:
|
||||
Você também pode aninhar arrays dentro de outros arrays, como abaixo:
|
||||
|
||||
```js
|
||||
[["Bulls", 23], ["White Sox", 45]]
|
||||
```
|
||||
|
||||
This is also called a <dfn>multi-dimensional array</dfn>.
|
||||
Isso é chamado um <dfn>array multidimensional</dfn>.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a nested array called `myArray`.
|
||||
Crie um array aninhado chamado de `myArray`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should have at least one array nested within another array.
|
||||
`myArray` deve ter pelo menos um array aninhado dentro de outro array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(myArray) && myArray.some(Array.isArray));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244e1
|
||||
title: Nesting For Loops
|
||||
title: Aninhando Laços For
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRn6GHM'
|
||||
forumTopicId: 18248
|
||||
@ -9,7 +9,7 @@ dashedName: nesting-for-loops
|
||||
|
||||
# --description--
|
||||
|
||||
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:
|
||||
Se você possui um array multidimensional, você pode usar a mesma lógica no ponto de passagem anterior para iterar através ambos os arrays e qualquer sub-arrays. Aqui está um exemplo:
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
@ -22,21 +22,21 @@ for (var i=0; i < arr.length; i++) {
|
||||
}
|
||||
```
|
||||
|
||||
This outputs each sub-element in `arr` one at a time. Note that for the inner loop, we are checking the `.length` of `arr[i]`, since `arr[i]` is itself an array.
|
||||
Isso exibi no console cada sub elemento dentro de `arr`, um de cada vez. Note que para o laço interno, nós estamos verificando a propriedade `.length` de `arr[i]`, desde que `arr[i]` também é um array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify function `multiplyAll` so that it returns the product of all the numbers in the sub-arrays of `arr`.
|
||||
Modifique a função `multiplyAll` para que retorne o produto de todos os números nos sub arrays de `arr`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`multiplyAll([[1],[2],[3]])` should return `6`
|
||||
`multiplyAll([[1],[2],[3]])` deve retornar `6`
|
||||
|
||||
```js
|
||||
assert(multiplyAll([[1], [2], [3]]) === 6);
|
||||
```
|
||||
|
||||
`multiplyAll([[1,2],[3,4],[5,6,7]])` should return `5040`
|
||||
`multiplyAll([[1,2],[3,4],[5,6,7]])` deve retornar `5040`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` should return `54`
|
||||
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` deve retornar `54`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bd
|
||||
title: Passing Values to Functions with Arguments
|
||||
title: Passando Valores para Funções com Argumentos
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy8rahW'
|
||||
forumTopicId: 18254
|
||||
@ -9,9 +9,9 @@ dashedName: passing-values-to-functions-with-arguments
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Parameters</dfn> are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or <dfn>"passed"</dfn>) into a function when it is called are known as <dfn>arguments</dfn>.
|
||||
<dfn>Parâmetros</dfn> são variáveis que atuam como espaços reservados para os valores que são passados para uma função, quando ela é chamada. Quando uma função é definida, normalmente ela é definida junto com um ou mais parâmetros. Os valores reais que são entradas de (ou <dfn>"passadas"</dfn> para) uma função quando ela é chamada são conhecidos como <dfn>argumentos</dfn>.
|
||||
|
||||
Here is a function with two parameters, `param1` and `param2`:
|
||||
Aqui está uma função com dois parâmetros, `param1` e `param2`:
|
||||
|
||||
```js
|
||||
function testFun(param1, param2) {
|
||||
@ -19,21 +19,21 @@ function testFun(param1, param2) {
|
||||
}
|
||||
```
|
||||
|
||||
Then we can call `testFun` like this: `testFun("Hello", "World");`. We have passed two string arguments, `Hello` and `World`. Inside the function, `param1` will equal the string `Hello` and `param2` will equal the string `World`. Note that you could call `testFun` again with different arguments and the parameters would take on the value of the new arguments.
|
||||
Então podemos chamar o `testFun` dessa forma: `testFun("Hello", "World");`. Passamos dois argumentos do tipo string, `Hello` e `World`. Dentro da função, `param1` será igual à string `Hello` e `param2` será igual à string `World`. Note que você poderia chamar o `testFun` novamente com diferentes argumentos e os parâmetros assumiriam o valor dos novos argumentos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
<ol><li>Create a function called <code>functionWithArgs</code> that accepts two arguments and outputs their sum to the dev console.</li><li>Call the function with two numbers as arguments.</li></ol>
|
||||
<ol><li>Crie uma função chamada <code>functionWithArgs</code> que aceita dois argumentos e exibe seus valores no console de desenvolvimento.</li><li>Chame a função com dois números como argumentos.</li></ol>
|
||||
|
||||
# --hints--
|
||||
|
||||
`functionWithArgs` should be a function.
|
||||
`functionWithArgs` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof functionWithArgs === 'function');
|
||||
```
|
||||
|
||||
`functionWithArgs(1,2)` should output `3`.
|
||||
`functionWithArgs(1,2)` deve exibir no console `3`.
|
||||
|
||||
```js
|
||||
if (typeof functionWithArgs === 'function') {
|
||||
@ -44,7 +44,7 @@ if (typeof functionWithArgs === 'function') {
|
||||
assert(logOutput == 3);
|
||||
```
|
||||
|
||||
`functionWithArgs(7,9)` should output `16`.
|
||||
`functionWithArgs(7,9)` deve exibir no console `16`.
|
||||
|
||||
```js
|
||||
if (typeof functionWithArgs === 'function') {
|
||||
@ -55,7 +55,7 @@ if (typeof functionWithArgs === 'function') {
|
||||
assert(logOutput == 16);
|
||||
```
|
||||
|
||||
You should call `functionWithArgs` with two numbers after you define it.
|
||||
Você deve chamar a função `functionWithArgs` com dois números depois de defini-la.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 599a789b454f2bbd91a3ff4d
|
||||
title: Practice comparing different values
|
||||
title: Pratique comparar diferentes valores
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm8PqCa'
|
||||
forumTopicId: 301174
|
||||
@ -9,42 +9,42 @@ dashedName: practice-comparing-different-values
|
||||
|
||||
# --description--
|
||||
|
||||
In the last two challenges, we learned about the equality operator (`==`) and the strict equality operator (`===`). Let's do a quick review and practice using these operators some more.
|
||||
Nos últimos dois desafios, aprendemos sobre o operador de igualdade (`==`) e o operador de igualdade estrita (`===`). Vamos fazer uma breve revisão e praticar usando esses operadores mais uma vez.
|
||||
|
||||
If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.
|
||||
Se os valores sendo comparados não são do mesmo tipo, o operador de igualdade irá fazer a conversão de tipo e, então, avaliar os valores. No entanto, o operador de igualdade estrita irá comparar ambos os tipos de dados e os valores, sem converter de um tipo para outro.
|
||||
|
||||
**Examples**
|
||||
**Exemplos**
|
||||
|
||||
`3 == '3'` returns `true` because JavaScript performs type conversion from string to number. `3 === '3'` returns false because the types are different and type conversion is not performed.
|
||||
`3 == '3'` retorna `true` porque JavaScript faz a conversão de tipo de string para número. `3 === '3'` retorna falso porque os tipos são diferentes e não é feita a conversão de tipo.
|
||||
|
||||
**Note:** In JavaScript, you can determine the type of a variable or a value with the `typeof` operator, as follows:
|
||||
**Nota:** Em JavaScript, você pode determinar o tipo de uma variável ou de um valor, com o operador `typeof`, como se segue:
|
||||
|
||||
```js
|
||||
typeof 3
|
||||
typeof '3'
|
||||
```
|
||||
|
||||
`typeof 3` returns the string `number`, and `typeof '3'` returns the string `string`.
|
||||
`typeof 3` retorna a string `number` e `typeof '3'` retorna a string `string`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The `compareEquality` function in the editor compares two values using the equality operator. Modify the function so that it returns the string `Equal` only when the values are strictly equal.
|
||||
A função `compareEquality` no editor compara dois valores usando o operador de igualdade. Modifique a função para que ela retorne a string `Equal` apenas quando os valores forem estritamente iguais.
|
||||
|
||||
# --hints--
|
||||
|
||||
`compareEquality(10, "10")` should return the string `Not Equal`
|
||||
`compareEquality(10, "10")` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(compareEquality(10, '10') === 'Not Equal');
|
||||
```
|
||||
|
||||
`compareEquality("20", 20)` should return the string `Not Equal`
|
||||
`compareEquality("20", 20)` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(compareEquality('20', 20) === 'Not Equal');
|
||||
```
|
||||
|
||||
You should use the `===` operator
|
||||
Você deve usar o operador `===`
|
||||
|
||||
```js
|
||||
assert(code.match(/===/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5688e62ea601b2482ff8422b
|
||||
title: Profile Lookup
|
||||
title: Busca de Perfil
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqW2Cg'
|
||||
forumTopicId: 18259
|
||||
@ -9,27 +9,27 @@ dashedName: profile-lookup
|
||||
|
||||
# --description--
|
||||
|
||||
We have an array of objects representing different people in our contacts lists.
|
||||
Nós temos um array de objetos representando pessoas diferentes nas nossas listas de contatos.
|
||||
|
||||
A `lookUpProfile` function that takes `name` and a property (`prop`) as arguments has been pre-written for you.
|
||||
Uma função `lookUpProfile`, que recebe `name` e uma propriedade (`prop`) como argumentos, foi pré-escrita para você.
|
||||
|
||||
The function should check if `name` is an actual contact's `firstName` and the given property (`prop`) is a property of that contact.
|
||||
A função deve verificar se `name` é o `firstName` (primeiro nome) de um contato e se a propriedade passada (`prop`) é uma propriedade daquele contato.
|
||||
|
||||
If both are true, then return the "value" of that property.
|
||||
Se ambos forem verdadeiros, então retorne o "valor" daquela propriedade.
|
||||
|
||||
If `name` does not correspond to any contacts then return the string `No such contact`.
|
||||
Se `name` não corresponder a nenhum dos contatos, então retorne a string `No such contact`.
|
||||
|
||||
If `prop` does not correspond to any valid properties of a contact found to match `name` then return the string `No such property`.
|
||||
Se `prop` não corresponder a nenhuma propriedade válida de um contato encontrado para coincidir com `name` então retorne a string `No such property`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lookUpProfile("Kristian", "lastName")` should return the string `Vos`
|
||||
`lookUpProfile("Kristian", "lastName")` deve retornar a string `Vos`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Kristian', 'lastName') === 'Vos');
|
||||
```
|
||||
|
||||
`lookUpProfile("Sherlock", "likes")` should return `["Intriguing Cases", "Violin"]`
|
||||
`lookUpProfile("Sherlock", "likes")` deve retornar `["Intriguing Cases", "Violin"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
|
||||
@ -38,25 +38,25 @@ assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`lookUpProfile("Harry", "likes")` should return an array
|
||||
`lookUpProfile("Harry", "likes")` deve retornar um array
|
||||
|
||||
```js
|
||||
assert(typeof lookUpProfile('Harry', 'likes') === 'object');
|
||||
```
|
||||
|
||||
`lookUpProfile("Bob", "number")` should return the string `No such contact`
|
||||
`lookUpProfile("Bob", "number")` deve retornar a string `No such contact`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Bob', 'number') === 'No such contact');
|
||||
```
|
||||
|
||||
`lookUpProfile("Bob", "potato")` should return the string `No such contact`
|
||||
`lookUpProfile("Bob", "potato")` deve retornar a string `No such contact`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Bob', 'potato') === 'No such contact');
|
||||
```
|
||||
|
||||
`lookUpProfile("Akira", "address")` should return the string `No such property`
|
||||
`lookUpProfile("Akira", "address")` deve retornar a string `No such property`
|
||||
|
||||
```js
|
||||
assert(lookUpProfile('Akira', 'address') === 'No such property');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b4
|
||||
title: Quoting Strings with Single Quotes
|
||||
title: Cercando uma String com Aspas Simples
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmnhM'
|
||||
forumTopicId: 18260
|
||||
@ -9,41 +9,41 @@ dashedName: quoting-strings-with-single-quotes
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>String</dfn> values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote. Unlike some other programming languages, single and double quotes work the same in JavaScript.
|
||||
Valores de <dfn>String</dfn> em JavaScript podem ser escritas com aspas simples ou duplas, desde que você comece e termine com o mesmo tipo de aspas. Diferente de outras linguagens de programação, aspas simples e duplas funcionam da mesma forma em JavaScript.
|
||||
|
||||
```js
|
||||
doubleQuoteStr = "This is a string";
|
||||
singleQuoteStr = 'This is also a string';
|
||||
```
|
||||
|
||||
The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes. Another use for it would be saving an `<a>` tag with various attributes in quotes, all within a string.
|
||||
O motivo pelo qual você pode querer usar um tipo de aspas no lugar da outra, é se você vir a querer usar ambas em uma string. Isso pode acontecer se você quiser salvar uma conversa em uma string e ter a conversa entre aspas. Outro uso para isso seria salvar uma tag `<a>` com vários atributos em aspas, tudo dentro de uma string.
|
||||
|
||||
```js
|
||||
conversation = 'Finn exclaims to Jake, "Algebraic!"';
|
||||
```
|
||||
|
||||
However, this becomes a problem if you need to use the outermost quotes within it. Remember, a string has the same kind of quote at the beginning and end. But if you have that same quote somewhere in the middle, the string will stop early and throw an error.
|
||||
Porém, isso se torna um problema se você precisar usar as aspas mais extremas dentro dela. Lembre-se, uma string tem o mesmo tipo de aspas no início e no final. Mas se você tem aquela mesma aspa em algum lugar no meio, a string irá terminar mais cedo e lançará um erro.
|
||||
|
||||
```js
|
||||
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
|
||||
badStr = 'Finn responds, "Let's go!"';
|
||||
```
|
||||
|
||||
Here `badStr` will throw an error.
|
||||
Aqui `badStr` lançará um erro.
|
||||
|
||||
In the <dfn>goodStr</dfn> above, you can use both quotes safely by using the backslash `\` as an escape character.
|
||||
Na string <dfn>goodStr</dfn> acima, você pode usar ambas as aspas com segurança ao usar a barra invertida `\` como um caractere de escapamento.
|
||||
|
||||
**Note:** The backslash `\` should not be confused with the forward slash `/`. They do not do the same thing.
|
||||
**Nota:** A barra invertida `\` não deve ser confundida com a barra comum `/`. Elas não fazem a mesma coisa.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the provided string to a string with single quotes at the beginning and end and no escape characters.
|
||||
Altere a string fornecida para uma string com aspas simples no início e no final e sem caracteres de escapamento.
|
||||
|
||||
Right now, the `<a>` tag in the string uses double quotes everywhere. You will need to change the outer quotes to single quotes so you can remove the escape characters.
|
||||
Nesse momento, a tag `<a>` na string usa aspas duplas em todo canto. Você precisará alterar as aspas mais externas em aspas simples, para que você possa remover os caracteres de escapamento.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should remove all the backslashes (`\`).
|
||||
Você deve remover todas as barras invertidas (`\`).
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,7 +54,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should have two single quotes `'` and four double quotes `"`.
|
||||
Você deve ter duas aspas simples `'` e quatro aspas duplas `"`.
|
||||
|
||||
```js
|
||||
assert(code.match(/"/g).length === 4 && code.match(/'/g).length === 2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cf
|
||||
title: Record Collection
|
||||
title: Coleção de Disco
|
||||
challengeType: 1
|
||||
forumTopicId: 18261
|
||||
dashedName: record-collection
|
||||
@ -8,21 +8,21 @@ dashedName: record-collection
|
||||
|
||||
# --description--
|
||||
|
||||
You are given an object literal representing a part of your musical album collection. Each album has a unique id number as its key and several other properties. Not all albums have complete information.
|
||||
Você recebeu um objeto literal representando uma parte da sua coleção de álbuns musicais. Cada álbum possui um número de id único como sua chave e diversas outras propriedades. Nem todos os álbuns possuem informações completas.
|
||||
|
||||
You start with an `updateRecords` function that takes an object literal, `records`, containing the musical album collection, an `id`, a `prop` (like `artist` or `tracks`), and a `value`. Complete the function using the rules below to modify the object passed to the function.
|
||||
Você começa com uma função `updateRecords` que recebe um objeto literal, `records`, contendo a coleção de álbuns musicais, um `id`, uma </code>prop</code>(like `artist` ou `tracks`) e um `vlaue`. Complete a função usando as regras abaixo para modificar o objeto passado para a função.
|
||||
|
||||
- Your function must always return the entire record collection object.
|
||||
- If `prop` isn't `tracks` and `value` isn't an empty string, update or set that album's `prop` to `value`.
|
||||
- If `prop` is `tracks` but the album doesn't have a `tracks` property, create an empty array and add `value` to it.
|
||||
- If `prop` is `tracks` and `value` isn't an empty string, add `value` to the end of the album's existing `tracks` array.
|
||||
- If `value` is an empty string, delete the given `prop` property from the album.
|
||||
- Sua função precisa sempre retornar o objeto de coleção de discos completo.
|
||||
- Se `prop` não for `tracks` e `value` não for uma string vazia, atualize ou defina aquela `prop` do album como `value`.
|
||||
- Se `prop` for `tracks` mas o álbum não tiver uma propriedade `tracks`, crie um array vazio e adicione o `value` nesse array.
|
||||
- Se `prop` for `tracks` e `value` não for uma string vazia, adicione `value` ao final do array existente de `tracks` do álbum.
|
||||
- Se `value` for uma string vazia, remova a propriedade `prop` recebida do álbum.
|
||||
|
||||
**Note:** A copy of the `recordCollection` object is used for the tests.
|
||||
**Nota:** Uma cópia do objeto `recordCollection` é usada para testes.
|
||||
|
||||
# --hints--
|
||||
|
||||
After `updateRecords(recordCollection, 5439, "artist", "ABBA")`, `artist` should be the string `ABBA`
|
||||
Após `updateRecords(recordCollection, 5439, "artist", "ABBA")`, `artist` deve ser aa string `ABBA`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -31,7 +31,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
After `updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me")`, `tracks` should have the string `Take a Chance on Me` as the last element.
|
||||
Após `updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me")`, `tracks` deve ter a string `Take a Chance on Me` como último elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,14 +41,14 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
After `updateRecords(recordCollection, 2548, "artist", "")`, `artist` should not be set
|
||||
Após `updateRecords(recordCollection, 2548, "artist", "")`, `artist` não deve ser definido
|
||||
|
||||
```js
|
||||
updateRecords(_recordCollection, 2548, 'artist', '');
|
||||
assert(!_recordCollection[2548].hasOwnProperty('artist'));
|
||||
```
|
||||
|
||||
After `updateRecords(recordCollection, 1245, "tracks", "Addicted to Love")`, `tracks` should have the string `Addicted to Love` as the last element.
|
||||
Após `updateRecords(recordCollection, 1245, "tracks", "Addicted to Love")`, `tracks` deve ter a string `Addicted to Love` como o último elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -58,7 +58,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
After `updateRecords(recordCollection, 2468, "tracks", "Free")`, `tracks` should have the string `1999` as the first element.
|
||||
Após `updateRecords(recordCollection, 2468, "tracks", "Free")`, `tracks` deve ter a string `1999` como o último elemento. Após.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -68,14 +68,14 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
After `updateRecords(recordCollection, 2548, "tracks", "")`, `tracks` should not be set
|
||||
Após `updateRecords(recordCollection, 2548, "tracks", "")`, `tracks` não deve ser definido
|
||||
|
||||
```js
|
||||
updateRecords(_recordCollection, 2548, 'tracks', '');
|
||||
assert(!_recordCollection[2548].hasOwnProperty('tracks'));
|
||||
```
|
||||
|
||||
After `updateRecords(recordCollection, 1245, "albumTitle", "Riptide")`, `albumTitle` should be the string `Riptide`
|
||||
Após `updateRecords(recordCollection, 1245, "albumTitle", "Riptide")`, `albumTitle` deve ser a string `Riptide`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cfa3679138e7d9595b9d9d4
|
||||
title: Replace Loops using Recursion
|
||||
title: Substituir Laços com Recursividade
|
||||
challengeType: 1
|
||||
videoUrl: >-
|
||||
https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/
|
||||
@ -10,7 +10,7 @@ dashedName: replace-loops-using-recursion
|
||||
|
||||
# --description--
|
||||
|
||||
Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first `n` elements of an array to create the product of those elements. Using a `for` loop, you could do this:
|
||||
Recursividade é o conceito de que uma função pode ser chamada por ela mesmo. Para ajudar a entender isso, comece a pensar sobre a seguinte tarefa: multiplique os primeiros `n` elementos de um array para criar o produto desses elementos. Usando um laço `for`, você poderia fazer isso:
|
||||
|
||||
```js
|
||||
function multiply(arr, n) {
|
||||
@ -22,7 +22,7 @@ Recursion is the concept that a function can be expressed in terms of itself. To
|
||||
}
|
||||
```
|
||||
|
||||
However, notice that `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. That means you can rewrite `multiply` in terms of itself and never need to use a loop.
|
||||
No entanto, note que `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. Isso significa que você pode rescreve `multiply` dentro da própria função e nunca precisar de usar um laço.
|
||||
|
||||
```js
|
||||
function multiply(arr, n) {
|
||||
@ -34,35 +34,35 @@ However, notice that `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. Th
|
||||
}
|
||||
```
|
||||
|
||||
The recursive version of `multiply` breaks down like this. In the <dfn>base case</dfn>, where `n <= 0`, it returns 1. For larger values of `n`, it calls itself, but with `n - 1`. That function call is evaluated in the same way, calling `multiply` again until `n <= 0`. At this point, all the functions can return and the original `multiply` returns the answer.
|
||||
A versão recursiva de `multiply` fica dessa forma. No <dfn>caso de base</dfn>, onde `n <= 0`, ele retorna 1. Para valores maiores de `n`, a função chama a si mesmo, mas com `n - 1`. Essa chamada da função é avaliada da mesma forma, chamando `multiply` novamente até que `n <= 0`. Nesse ponto, todas as funções podem retornar e a função `multiply` original retorna a resposta.
|
||||
|
||||
**Note:** Recursive functions must have a base case when they return without calling the function again (in this example, when `n <= 0`), otherwise they can never finish executing.
|
||||
**Nota:** Funções recursivas precisam ter um caso base quando elas retornam sem chamar a função novamente (nesse exemplo, quando `n <= 0`), caso contrário, elas nunca irão parar de executar.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a recursive function, `sum(arr, n)`, that returns the sum of the first `n` elements of an array `arr`.
|
||||
Escreva uma função recursiva, `sum(arr, n)`, que retorna a soma dos primeiros `n` elementos de um array `arr`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum([1], 0)` should equal 0.
|
||||
`sum([1], 0)` deve ser igual a 0.
|
||||
|
||||
```js
|
||||
assert.equal(sum([1], 0), 0);
|
||||
```
|
||||
|
||||
`sum([2, 3, 4], 1)` should equal 2.
|
||||
`sum([2, 3, 4], 1)` deve ser igual a 2.
|
||||
|
||||
```js
|
||||
assert.equal(sum([2, 3, 4], 1), 2);
|
||||
```
|
||||
|
||||
`sum([2, 3, 4, 5], 3)` should equal 9.
|
||||
`sum([2, 3, 4, 5], 3)` deve ser igual a 9.
|
||||
|
||||
```js
|
||||
assert.equal(sum([2, 3, 4, 5], 3), 9);
|
||||
```
|
||||
|
||||
Your code should not rely on any kind of loops (`for` or `while` or higher order functions such as `forEach`, `map`, `filter`, or `reduce`.).
|
||||
Seu código não deve depender de nenhum laço (`for` ou `while` ou funções de ordem superior como as funções `forEach`, `map`, `filter` ou `reduce`.).
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -70,7 +70,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use recursion to solve this problem.
|
||||
Você deve usar recursividade para resolver o problema.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244e0
|
||||
title: Replacing If Else Chains with Switch
|
||||
title: Substituir Cadeias de If Else por Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c3JE8fy'
|
||||
forumTopicId: 18266
|
||||
@ -9,7 +9,7 @@ dashedName: replacing-if-else-chains-with-switch
|
||||
|
||||
# --description--
|
||||
|
||||
If you have many options to choose from, a `switch` statement can be easier to write than many chained `if`/`else if` statements. The following:
|
||||
Se você tiver muitas opções para escolher, uma instrução `switch` pode ser mais fácil de escrever do que muitas instruções `if`/`else if` encadeadas. O seguinte:
|
||||
|
||||
```js
|
||||
if (val === 1) {
|
||||
@ -21,7 +21,7 @@ if (val === 1) {
|
||||
}
|
||||
```
|
||||
|
||||
can be replaced with:
|
||||
pode ser substituído por:
|
||||
|
||||
```js
|
||||
switch(val) {
|
||||
@ -38,65 +38,65 @@ switch(val) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the chained `if`/`else if` statements into a `switch` statement.
|
||||
Altere a cadeia de instruções `if`/`else if` em um comando `switch`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not use any `else` statements anywhere in the editor
|
||||
Você não deve usar nenhuma instrução `else` em nenhum lugar no editor
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code));
|
||||
```
|
||||
|
||||
You should not use any `if` statements anywhere in the editor
|
||||
Você não deve usar nenhuma instrução `if` em nenhum lugar no editor
|
||||
|
||||
```js
|
||||
assert(!/if/g.test(code));
|
||||
```
|
||||
|
||||
You should have at least four `break` statements
|
||||
Você deve ter pelo menos instruções `break`
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length >= 4);
|
||||
```
|
||||
|
||||
`chainToSwitch("bob")` should be the string `Marley`
|
||||
`chainToSwitch("bob")` deve ser a string `Marley`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch('bob') === 'Marley');
|
||||
```
|
||||
|
||||
`chainToSwitch(42)` should be the string `The Answer`
|
||||
`chainToSwitch(42)` deve ser a string `The Answer`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(42) === 'The Answer');
|
||||
```
|
||||
|
||||
`chainToSwitch(1)` should be the string `There is no #1`
|
||||
`chainToSwitch(1)` deve ser a string `There is no #1`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(1) === 'There is no #1');
|
||||
```
|
||||
|
||||
`chainToSwitch(99)` should be the string `Missed me by this much!`
|
||||
`chainToSwitch(99)` deve ser a string `Missed me by this much!`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(99) === 'Missed me by this much!');
|
||||
```
|
||||
|
||||
`chainToSwitch(7)` should be the string `Ate Nine`
|
||||
`chainToSwitch(7)` deve ser a string `Ate Nine`
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(7) === 'Ate Nine');
|
||||
```
|
||||
|
||||
`chainToSwitch("John")` should be `""` (empty string)
|
||||
`chainToSwitch("John")` deve ser `""` (string vazia)
|
||||
|
||||
```js
|
||||
assert(chainToSwitch('John') === '');
|
||||
```
|
||||
|
||||
`chainToSwitch(156)` should be `""` (empty string)
|
||||
`chainToSwitch(156)` deve ser `""` (string vazia)
|
||||
|
||||
```js
|
||||
assert(chainToSwitch(156) === '');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c2
|
||||
title: Return a Value from a Function with Return
|
||||
title: Retorne um Valor de uma Função com Return
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87wue'
|
||||
forumTopicId: 18271
|
||||
@ -9,9 +9,9 @@ dashedName: return-a-value-from-a-function-with-return
|
||||
|
||||
# --description--
|
||||
|
||||
We can pass values into a function with <dfn>arguments</dfn>. You can use a `return` statement to send a value back out of a function.
|
||||
Nós podemos passar valores para uma função com <dfn>argumentos</dfn>. Você pode usar uma instrução `return` para enviar um valor para fora de uma função.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
function plusThree(num) {
|
||||
@ -20,35 +20,35 @@ function plusThree(num) {
|
||||
var answer = plusThree(5);
|
||||
```
|
||||
|
||||
`answer` has the value `8`.
|
||||
`answer` tem o valor de `8`.
|
||||
|
||||
`plusThree` takes an <dfn>argument</dfn> for `num` and returns a value equal to `num + 3`.
|
||||
`plusThree` recebe um <dfn>argumento</dfn> para `num` e retorna um valor igual a `num + 3`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function `timesFive` that accepts one argument, multiplies it by `5`, and returns the new value.
|
||||
Crie uma função `timesFive` que aceita um argumento, multiplica ele por `5` e retorna o novo valor.
|
||||
|
||||
# --hints--
|
||||
|
||||
`timesFive` should be a function
|
||||
`timesFive` deve ser uma função
|
||||
|
||||
```js
|
||||
assert(typeof timesFive === 'function');
|
||||
```
|
||||
|
||||
`timesFive(5)` should return `25`
|
||||
`timesFive(5)` deve retornar `25`
|
||||
|
||||
```js
|
||||
assert(timesFive(5) === 25);
|
||||
```
|
||||
|
||||
`timesFive(2)` should return `10`
|
||||
`timesFive(2)` deve retornar `10`
|
||||
|
||||
```js
|
||||
assert(timesFive(2) === 10);
|
||||
```
|
||||
|
||||
`timesFive(0)` should return `0`
|
||||
`timesFive(0)` deve retornar `0`
|
||||
|
||||
```js
|
||||
assert(timesFive(0) === 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c4
|
||||
title: Return Early Pattern for Functions
|
||||
title: Retornar o Padrão Inicial para Funções
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQe39Sq'
|
||||
forumTopicId: 18272
|
||||
@ -9,9 +9,9 @@ dashedName: return-early-pattern-for-functions
|
||||
|
||||
# --description--
|
||||
|
||||
When a `return` statement is reached, the execution of the current function stops and control returns to the calling location.
|
||||
Quando uma instrução `return` é alcançada, a execução da função atual para e retorna o código para o local da chamada da função.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
function myFun() {
|
||||
@ -22,54 +22,54 @@ function myFun() {
|
||||
myFun();
|
||||
```
|
||||
|
||||
The above will display the string `Hello` in the console, and return the string `World`. The string `byebye` will never display in the console, because the function exits at the `return` statement.
|
||||
O código acima exibirá no console a string `Hello`, e retorna a string `World`. A string `byebye` nunca irá ser exibida no console, porque a função termina na instrução `return`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the function `abTest` so that if `a` or `b` are less than `0` the function will immediately exit with a value of `undefined`.
|
||||
Modifique a função `abTest` para que se `a` ou `b` forem menores que `0` a função irá imediatamente terminar retornando o valor de `undefined`.
|
||||
|
||||
**Hint**
|
||||
Remember that [`undefined` is a keyword](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables), not a string.
|
||||
**Dica**
|
||||
Lembre-se que [`undefined` é uma palavra-chave](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables) e não uma string.
|
||||
|
||||
# --hints--
|
||||
|
||||
`abTest(2,2)` should return a number
|
||||
`abTest(2,2)` deve retornar um número
|
||||
|
||||
```js
|
||||
assert(typeof abTest(2, 2) === 'number');
|
||||
```
|
||||
|
||||
`abTest(2,2)` should return `8`
|
||||
`abTest(2,2)` deve retornar `8`
|
||||
|
||||
```js
|
||||
assert(abTest(2, 2) === 8);
|
||||
```
|
||||
|
||||
`abTest(-2,2)` should return `undefined`
|
||||
`abTest(-2,2)` deve retornar `undefined`
|
||||
|
||||
```js
|
||||
assert(abTest(-2, 2) === undefined);
|
||||
```
|
||||
|
||||
`abTest(2,-2)` should return `undefined`
|
||||
`abTest(2,-2)` deve retornar `undefined`
|
||||
|
||||
```js
|
||||
assert(abTest(2, -2) === undefined);
|
||||
```
|
||||
|
||||
`abTest(2,8)` should return `18`
|
||||
`abTest(2,8)` deve retornar `18`
|
||||
|
||||
```js
|
||||
assert(abTest(2, 8) === 18);
|
||||
```
|
||||
|
||||
`abTest(3,3)` should return `12`
|
||||
`abTest(3,3)` deve retornar `12`
|
||||
|
||||
```js
|
||||
assert(abTest(3, 3) === 12);
|
||||
```
|
||||
|
||||
`abTest(0,0)` should return `0`
|
||||
`abTest(0,0)` deve retornar `0`
|
||||
|
||||
```js
|
||||
assert(abTest(0, 0) === 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5679ceb97cbaa8c51670a16b
|
||||
title: Returning Boolean Values from Functions
|
||||
title: Retornando Valores Booleanos das Funções
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cp62qAQ'
|
||||
forumTopicId: 18273
|
||||
@ -9,9 +9,9 @@ dashedName: returning-boolean-values-from-functions
|
||||
|
||||
# --description--
|
||||
|
||||
You may recall from [Comparison with the Equality Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) that all comparison operators return a boolean `true` or `false` value.
|
||||
Você pode se lembrar de [Comparação com o Operador de Igualdade](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) que todas os operadores de comparação retornam um valor booleano `true` ou `false`.
|
||||
|
||||
Sometimes people use an `if/else` statement to do a comparison, like this:
|
||||
As vezes as pessoas usam uma instrução `if/else` para fazer uma comparação, dessa forma:
|
||||
|
||||
```js
|
||||
function isEqual(a,b) {
|
||||
@ -23,7 +23,7 @@ function isEqual(a,b) {
|
||||
}
|
||||
```
|
||||
|
||||
But there's a better way to do this. Since `===` returns `true` or `false`, we can return the result of the comparison:
|
||||
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) {
|
||||
@ -33,23 +33,23 @@ function isEqual(a,b) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the function `isLess` to remove the `if/else` statements.
|
||||
Corrija a função `isLess` para remover as instruções `if/else`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isLess(10,15)` should return `true`
|
||||
`isLess(10,15)` deve retornar `true`
|
||||
|
||||
```js
|
||||
assert(isLess(10, 15) === true);
|
||||
```
|
||||
|
||||
`isLess(15,10)` should return `false`
|
||||
`isLess(15,10)` deve retornar `false`
|
||||
|
||||
```js
|
||||
assert(isLess(15, 10) === false);
|
||||
```
|
||||
|
||||
You should not use any `if` or `else` statements
|
||||
Você não deve usar nenhuma das instruções `if` ou `else`
|
||||
|
||||
```js
|
||||
assert(!/if|else/g.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dd
|
||||
title: Selecting from Many Options with Switch Statements
|
||||
title: Selecionando de Muitas Opções com Instruções Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c4mv4fm'
|
||||
forumTopicId: 18277
|
||||
@ -9,9 +9,9 @@ dashedName: selecting-from-many-options-with-switch-statements
|
||||
|
||||
# --description--
|
||||
|
||||
If you have many options to choose from, use a <dfn>switch</dfn> statement. A `switch` statement tests a value and can have many <dfn>case</dfn> statements which define various possible values. Statements are executed from the first matched `case` value until a `break` is encountered.
|
||||
Se você possui muitas opções pra escolher, use uma instrução <dfn>switch</dfn>. Uma instrução `switch` testa um valor e pode ter muitas instruções <dfn>case</dfn> as quais definem os diversos valores possíveis. Instruções são executadas desde o primeiro `case` correspondente até que encontre um `break`.
|
||||
|
||||
Here is an example of a `switch` statement:
|
||||
Aqui está um exemplo de uma instrução `switch`:
|
||||
|
||||
```js
|
||||
switch(lowercaseLetter) {
|
||||
@ -24,11 +24,11 @@ switch(lowercaseLetter) {
|
||||
}
|
||||
```
|
||||
|
||||
`case` values are tested with strict equality (`===`). The `break` tells JavaScript to stop executing statements. If the `break` is omitted, the next statement will be executed.
|
||||
Valores `case` são testados com o operador de igualdade estrita (`===`). O `break` diz ao JavaScript parar a execução das instruções. Se o `break` for omitido, a próxima instrução case será executada.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a switch statement which tests `val` and sets `answer` for the following conditions:
|
||||
Escreva uma instrução switch que testa `val` e define `answer` para as seguintes condições:
|
||||
`1` - `alpha`
|
||||
`2` - `beta`
|
||||
`3` - `gamma`
|
||||
@ -36,37 +36,37 @@ Write a switch statement which tests `val` and sets `answer` for the following c
|
||||
|
||||
# --hints--
|
||||
|
||||
`caseInSwitch(1)` should have a value of the string `alpha`
|
||||
`caseInSwitch(1)` deve ter o valor da string `alpha`
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(1) === 'alpha');
|
||||
```
|
||||
|
||||
`caseInSwitch(2)` should have a value of the string `beta`
|
||||
`caseInSwitch(2)` deve ter o valor da string `beta`
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(2) === 'beta');
|
||||
```
|
||||
|
||||
`caseInSwitch(3)` should have a value of the string `gamma`
|
||||
`caseInSwitch(3)` deve ter o valor da string `gamma`
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(3) === 'gamma');
|
||||
```
|
||||
|
||||
`caseInSwitch(4)` should have a value of the string `delta`
|
||||
`caseInSwitch(4)` deve ter o valor da string `delta`
|
||||
|
||||
```js
|
||||
assert(caseInSwitch(4) === 'delta');
|
||||
```
|
||||
|
||||
You should not use any `if` or `else` statements
|
||||
Você não deve usar nenhuma instrução `if` ou `else`
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
You should have at least 3 `break` statements
|
||||
Você deve ter pelo menos 3 instruções `break`
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length > 2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244bc
|
||||
title: Shopping List
|
||||
title: Lista de Compras
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9MEKHZ'
|
||||
forumTopicId: 18280
|
||||
@ -9,37 +9,37 @@ dashedName: shopping-list
|
||||
|
||||
# --description--
|
||||
|
||||
Create a shopping list in the variable `myList`. The list should be a multi-dimensional array containing several sub-arrays.
|
||||
Crie uma lista de compras na variável `myList`. A lista deve ser um array multidimensional contendo diversos sub arrays.
|
||||
|
||||
The first element in each sub-array should contain a string with the name of the item. The second element should be a number representing the quantity i.e.
|
||||
O primeiro elemento em cada sub array deve conter uma string com o nome do item. O segundo elemento deve ser um número representando a quantidade i.e.
|
||||
|
||||
```js
|
||||
["Chocolate Bar", 15]
|
||||
```
|
||||
|
||||
There should be at least 5 sub-arrays in the list.
|
||||
Deve ter pelo menos 5 sub arrays na lista.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myList` should be an array.
|
||||
`myList` deve ser um array.
|
||||
|
||||
```js
|
||||
assert(isArray);
|
||||
```
|
||||
|
||||
The first elements in each of your sub-arrays should all be strings.
|
||||
Os primeiros elementos em cada um dos seus sub arrays devem ser todos strings.
|
||||
|
||||
```js
|
||||
assert(hasString);
|
||||
```
|
||||
|
||||
The second elements in each of your sub-arrays should all be numbers.
|
||||
Os segundos elementos em cada um de seus sub arrays devem ser todos números.
|
||||
|
||||
```js
|
||||
assert(hasNumber);
|
||||
```
|
||||
|
||||
You should have at least 5 items in your list.
|
||||
Você deve ter pelo menos 5 items na sua lista.
|
||||
|
||||
```js
|
||||
assert(count > 4);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c6
|
||||
title: Stand in Line
|
||||
title: Fique na Linha
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8Q8tP'
|
||||
forumTopicId: 18307
|
||||
@ -9,41 +9,41 @@ dashedName: stand-in-line
|
||||
|
||||
# --description--
|
||||
|
||||
In Computer Science a <dfn>queue</dfn> is an abstract <dfn>Data Structure</dfn> where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.
|
||||
Na Ciência da Computação uma <dfn>fila</dfn> é uma <dfn>estrutura de dados</dfn> abstrata onde itens são mantidos em ordem. Novos itens podem ser adicionados no final da fila e itens mais antigos são removidos do início da fila.
|
||||
|
||||
Write a function `nextInLine` which takes an array (`arr`) and a number (`item`) as arguments.
|
||||
Escreva a função `nextInLine` a qual recebe um array (`arr`) e um número (`item`) como argumentos.
|
||||
|
||||
Add the number to the end of the array, then remove the first element of the array.
|
||||
Adicione o número no final do array e então remova o primeiro elemento do array.
|
||||
|
||||
The `nextInLine` function should then return the element that was removed.
|
||||
A função `nextInLine` deve, em seguida, retornar o elemento que foi removido.
|
||||
|
||||
# --hints--
|
||||
|
||||
`nextInLine([], 5)` should return a number.
|
||||
`nextInLine([], 5)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert.isNumber(nextInLine([], 5));
|
||||
```
|
||||
|
||||
`nextInLine([], 1)` should return `1`
|
||||
`nextInLine([], 1)` deve retonar `1`
|
||||
|
||||
```js
|
||||
assert(nextInLine([], 1) === 1);
|
||||
```
|
||||
|
||||
`nextInLine([2], 1)` should return `2`
|
||||
`nextInLine([2], 1)` deve retornar `2`
|
||||
|
||||
```js
|
||||
assert(nextInLine([2], 1) === 2);
|
||||
```
|
||||
|
||||
`nextInLine([5,6,7,8,9], 1)` should return `5`
|
||||
`nextInLine([5,6,7,8,9], 1)` deve retornar `5`
|
||||
|
||||
```js
|
||||
assert(nextInLine([5, 6, 7, 8, 9], 1) === 5);
|
||||
```
|
||||
|
||||
After `nextInLine(testArr, 10)`, `testArr[4]` should be `10`
|
||||
Após `nextInLine(testArr, 10)`, `testArr[4]` deve ser `10`
|
||||
|
||||
```js
|
||||
nextInLine(testArr, 10);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7993c9c69feddfaeb8bdef
|
||||
title: Store Multiple Values in one Variable using JavaScript Arrays
|
||||
title: Armazene Múltiplos Valores em uma Variável usando Arrays JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/crZQWAm'
|
||||
forumTopicId: 18309
|
||||
@ -9,9 +9,9 @@ dashedName: store-multiple-values-in-one-variable-using-javascript-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
With JavaScript `array` variables, we can store several pieces of data in one place.
|
||||
Com as variáveis de `array` em JavaScript, podemos armazenar diversos pedaços de dados em um único lugar.
|
||||
|
||||
You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:
|
||||
Você começa uma declaração de um array com a abertura de um colchetes, terminando com o fechamento do colchetes e colocando vírgula entre cada entrada, dessa forma:
|
||||
|
||||
```js
|
||||
var sandwich = ["peanut butter", "jelly", "bread"]
|
||||
@ -19,23 +19,23 @@ var sandwich = ["peanut butter", "jelly", "bread"]
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the new array `myArray` so that it contains both a string and a number (in that order).
|
||||
Modifique o novo array `myArray` para que contenha ambos uma string e um número (nessa ordem).
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray` should be an array.
|
||||
`myArray` deve ser um array.
|
||||
|
||||
```js
|
||||
assert(typeof myArray == 'object');
|
||||
```
|
||||
|
||||
The first item in `myArray` should be a string.
|
||||
O primeiro item de `myArray` deve ser uma string.
|
||||
|
||||
```js
|
||||
assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string');
|
||||
```
|
||||
|
||||
The second item in `myArray` should be a number.
|
||||
O segundo item de `myArray` deve ser um número.
|
||||
|
||||
```js
|
||||
assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244a8
|
||||
title: Storing Values with the Assignment Operator
|
||||
title: Armazenando Valores com o Operador de Atribuição
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cEanysE'
|
||||
forumTopicId: 18310
|
||||
@ -9,36 +9,36 @@ dashedName: storing-values-with-the-assignment-operator
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, you can store a value in a variable with the <dfn>assignment</dfn> operator (`=`).
|
||||
Em JavaScript, você pode armazenar um valor em uma variável com o operador de <dfn>atribuição</dfn> (`=`).
|
||||
|
||||
```js
|
||||
myVariable = 5;
|
||||
```
|
||||
|
||||
This assigns the `Number` value `5` to `myVariable`.
|
||||
Isso atribui o valor de `Number` `5` para `myVariable`.
|
||||
|
||||
If there are any calculations to the right of the `=` operator, those are performed before the value is assigned to the variable on the left of the operator.
|
||||
Se há qualquer cálculo a direita do operador `=`, esses cálculos são executados antes do valor ser atribuído à variável na esquerda do operador.
|
||||
|
||||
```js
|
||||
var myVar;
|
||||
myVar = 5;
|
||||
```
|
||||
|
||||
First, this code creates a variable named `myVar`. Then, the code assigns `5` to `myVar`. Now, if `myVar` appears again in the code, the program will treat it as if it is `5`.
|
||||
Primeiro, esse código cria uma variável chamada `myVar`. Em seguida, o código atribui `5` para `myVar`. Agora, se `myVar` aparece novamente no código, o programa irá tratar como se fosse `5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assign the value `7` to variable `a`.
|
||||
Atribua o valor `7` para a variável `a`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change code above the specified comment.
|
||||
Você não deve alterar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(/var a;/.test(code));
|
||||
```
|
||||
|
||||
`a` should have a value of 7.
|
||||
`a` deve ter o valor de 7.
|
||||
|
||||
```js
|
||||
assert(typeof a === 'number' && a === 7);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb4bdef
|
||||
title: Subtract One Number from Another with JavaScript
|
||||
title: Subtraia Um Número de Outro com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cP3yQtk'
|
||||
forumTopicId: 18314
|
||||
@ -9,30 +9,30 @@ dashedName: subtract-one-number-from-another-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
We can also subtract one number from another.
|
||||
Nós também podemos subtrair um número de outro.
|
||||
|
||||
JavaScript uses the `-` symbol for subtraction.
|
||||
JavaScript usa o símbolo `-` para subtração.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
myVar = 12 - 6;
|
||||
```
|
||||
|
||||
`myVar` would have the value `6`.
|
||||
`myVar` teria o valor `6`.
|
||||
# --instructions--
|
||||
|
||||
Change the `0` so the difference is `12`.
|
||||
Altere o `0` para que a variável difference seja igual a `12`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `difference` should be equal to 12.
|
||||
A variável `difference` deve ser igual a 12.
|
||||
|
||||
```js
|
||||
assert(difference === 12);
|
||||
```
|
||||
|
||||
You should only subtract one number from 45.
|
||||
Você só deve subtrair um número de 45.
|
||||
|
||||
```js
|
||||
assert(/difference=45-33;?/.test(__helpers.removeWhiteSpace(code)));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 567af2437cbaa8c51670a16c
|
||||
title: Testing Objects for Properties
|
||||
title: Testando Objetos por Propriedades
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6Wz4ySr'
|
||||
forumTopicId: 18324
|
||||
@ -9,9 +9,9 @@ dashedName: testing-objects-for-properties
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes it is useful to check if the property of a given object exists or not. We can use the `.hasOwnProperty(propname)` method of objects to determine if that object has the given property name. `.hasOwnProperty()` returns `true` or `false` if the property is found or not.
|
||||
Às vezes é útil verificar se a propriedade de um determinado objeto existe ou não. Podemos usar o método de objetos `.hasOwnProperty(propname)` para determinar se aquele objeto possui o nome de propriedade fornecido. `.hasOwnProperty()` retorna `true` ou `false` se a propriedade for encontrada ou não.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
@ -22,15 +22,15 @@ myObj.hasOwnProperty("top");
|
||||
myObj.hasOwnProperty("middle");
|
||||
```
|
||||
|
||||
The first `hasOwnProperty` returns `true`, while the second returns `false`.
|
||||
O primeiro `hasOwnProperty` retorna `true`, enquanto o segundo retorna `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the function `checkObj` to test if an object passed to the function (`obj`) contains a specific property (`checkProp`). If the property is found, return that property's value. If not, return `"Not Found"`.
|
||||
Modifique a função `checkObj` para verificar se um objeto passado para a função (`obj`) contém uma propriedade específica (`checkProp`). Se a propriedade for encontrada, retorne o valor da propriedade. Se não, retorne `"Not Found"`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return the string `pony`.
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` deve retornar a string `pony`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return the string `kitten`.
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` deve retornar a string `kitten`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -46,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return the string `Not Found`.
|
||||
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` deve retornar a string `Not Found`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -55,19 +55,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`checkObj({city: "Seattle"}, "city")` should return the string `Seattle`.
|
||||
`checkObj({city: "Seattle"}, "city")` deve retornar a string `Seattle`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle');
|
||||
```
|
||||
|
||||
`checkObj({city: "Seattle"}, "district")` should return the string `Not Found`.
|
||||
`checkObj({city: "Seattle"}, "district")` deve retornar a string `Not Found`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found');
|
||||
```
|
||||
|
||||
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return the string `Not Found`.
|
||||
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` deve retornar a string `Not Found`.
|
||||
|
||||
```js
|
||||
assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ba
|
||||
title: Understand String Immutability
|
||||
title: Entendendo a Imutabilidade das Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWPVaUR'
|
||||
forumTopicId: 18331
|
||||
@ -9,16 +9,16 @@ dashedName: understand-string-immutability
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, `String` values are <dfn>immutable</dfn>, which means that they cannot be altered once created.
|
||||
Em JavaScript, valores `String` são <dfn>imutáveis</dfn>, o que significa que elas não podem ser alteradas após serem criadas.
|
||||
|
||||
For example, the following code:
|
||||
Por exemplo, o código a seguir:
|
||||
|
||||
```js
|
||||
var myStr = "Bob";
|
||||
myStr[0] = "J";
|
||||
```
|
||||
|
||||
cannot change the value of `myStr` to `Job`, because the contents of `myStr` cannot be altered. Note that this does *not* mean that `myStr` cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change `myStr` would be to assign it with a new string, like this:
|
||||
não é possível alterar o valor de `myStr` para `Job`, porque o conteúdo de `myStr` não pode ser alterado. Note que isso *não* significa que `myStr` não pode ser alterado, apenas que os caracteres individuais de uma <dfn>string literal</dfn> não pode ser alterado. A única forma de alterar `myStr` seria atribuindo-a com uma nova string, dessa forma:
|
||||
|
||||
```js
|
||||
var myStr = "Bob";
|
||||
@ -27,17 +27,17 @@ myStr = "Job";
|
||||
|
||||
# --instructions--
|
||||
|
||||
Correct the assignment to `myStr` so it contains the string value of `Hello World` using the approach shown in the example above.
|
||||
Corrija a atribuição para `myStr` para que contenha o valor `Hello World` (string) usando a abordagem mostrada no exemplo acima.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` should have a value of the string `Hello World`.
|
||||
`myStr` deve ter o valor da string `HelloWorld`.
|
||||
|
||||
```js
|
||||
assert(myStr === 'Hello World');
|
||||
```
|
||||
|
||||
You should not change the code above the specified comment.
|
||||
Você não deve alterar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(/myStr = "Jello World"/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb5bdef
|
||||
title: Understanding Boolean Values
|
||||
title: Entendendo Valores Booleanos
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9Me8t4'
|
||||
forumTopicId: 301176
|
||||
@ -9,23 +9,23 @@ dashedName: understanding-boolean-values
|
||||
|
||||
# --description--
|
||||
|
||||
Another data type is the <dfn>Boolean</dfn>. Booleans may only be one of two values: `true` or `false`. They are basically little on-off switches, where `true` is on and `false` is off. These two states are mutually exclusive.
|
||||
Outro tipo de dado é o <dfn>Boolean</dfn>. Booleanos podem ser apenas dois valores: `true` ou `false`. Eles basicamente são interruptores pequenos, onde `true` é ligado e `false` é desligado. Esses dois estados são mutuamente exclusivos.
|
||||
|
||||
**Note:** Boolean values are never written with quotes. The strings `"true"` and `"false"` are not Boolean and have no special meaning in JavaScript.
|
||||
**Nota:** Valores booleanos nunca são escritos com aspas. As strings `"true"` e `"false"` não são Booleanos e não tem nenhum significado especial em JavaScript.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the `welcomeToBooleans` function so that it returns `true` instead of `false` when the run button is clicked.
|
||||
Modifique a função `welcomeToBooleans` para que retorne `true` ao invés de `false` quando o botão de correr for clicado.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `welcomeToBooleans()` function should return a Boolean (`true` or `false`) value.
|
||||
A função `welcomeToBooleans()` deve retornar um valor Booleano (`true` ou `false`).
|
||||
|
||||
```js
|
||||
assert(typeof welcomeToBooleans() === 'boolean');
|
||||
```
|
||||
|
||||
`welcomeToBooleans()` should return `true`.
|
||||
`welcomeToBooleans()` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(welcomeToBooleans() === true);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ab
|
||||
title: Understanding Case Sensitivity in Variables
|
||||
title: Entendendo a Sensibilidade a Caracteres Maiúsculos e Minúsculos em Variáveis
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cd6GDcD'
|
||||
forumTopicId: 18334
|
||||
@ -9,15 +9,15 @@ dashedName: understanding-case-sensitivity-in-variables
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript all variables and function names are case sensitive. This means that capitalization matters.
|
||||
Em JavaScript todas os nomes de variáveis e funções são sensíveis a caracteres maiúsculos e minúsculos. Isso significa que a capitalização importa.
|
||||
|
||||
`MYVAR` is not the same as `MyVar` nor `myvar`. It is possible to have multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you *do not* use this language feature.
|
||||
`MYVAR` não é o mesmo que `MyVar` nem `myvar`. É possível ter diversas variáveis distintas com o mesmo nome mas com capitalização diferente. É extremamente recomendado pelo bem da clareza, que você *não* use esse recurso da linguagem.
|
||||
|
||||
**Best Practice**
|
||||
**Melhores Práticas**
|
||||
|
||||
Write variable names in JavaScript in <dfn>camelCase</dfn>. In <dfn>camelCase</dfn>, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.
|
||||
Escreva nomes de variáveis em JavaScript em <dfn>camelCase</dfn>. Em <dfn>camelCase</dfn>, nomes de variáveis com mais de uma palavra possuem a primeira palavra toda em minúscula e a primeira letra de cada palavra subsequente capitalizada.
|
||||
|
||||
**Examples:**
|
||||
**Exemplos:**
|
||||
|
||||
```js
|
||||
var someVariable;
|
||||
@ -27,19 +27,19 @@ var thisVariableNameIsSoLong;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the existing declarations and assignments so their names use <dfn>camelCase</dfn>.
|
||||
Modifique as declarações e atribuições existentes para que seus nomes usem <dfn>camelCase</dfn>.
|
||||
|
||||
Do not create any new variables.
|
||||
Não crie nenhuma variável nova.
|
||||
|
||||
# --hints--
|
||||
|
||||
`studlyCapVar` should be defined and have a value of `10`.
|
||||
`studlyCapVar` deve ser definido e ter um valor de `10`.
|
||||
|
||||
```js
|
||||
assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10);
|
||||
```
|
||||
|
||||
`properCamelCase` should be defined and have a value of the string `A String`.
|
||||
`properCamelCase` deve ser definida e ter o valor da string `A String`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -47,25 +47,25 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`titleCaseOver` should be defined and have a value of `9000`.
|
||||
`titleCaseOver` deve ser definida e ter o valor de `9000`.
|
||||
|
||||
```js
|
||||
assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000);
|
||||
```
|
||||
|
||||
`studlyCapVar` should use camelCase in both declaration and assignment sections.
|
||||
`studlyCapVar` deve usar camelCase em ambas as seções de declaração e atribuição.
|
||||
|
||||
```js
|
||||
assert(code.match(/studlyCapVar/g).length === 2);
|
||||
```
|
||||
|
||||
`properCamelCase` should use camelCase in both declaration and assignment sections.
|
||||
`properCamelCase` deve usar camelCase em ambas as seções de declaração e atribuição.
|
||||
|
||||
```js
|
||||
assert(code.match(/properCamelCase/g).length === 2);
|
||||
```
|
||||
|
||||
`titleCaseOver` should use camelCase in both declaration and assignment sections.
|
||||
`titleCaseOver` deve usar camelCase em ambas as seções de declaração e atribuição.
|
||||
|
||||
```js
|
||||
assert(code.match(/titleCaseOver/g).length === 2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 598e8944f009e646fc236146
|
||||
title: Understanding Undefined Value returned from a Function
|
||||
title: Entendendo Valor Undefined retornado de uma Função
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2p7cL'
|
||||
forumTopicId: 301177
|
||||
@ -9,9 +9,9 @@ dashedName: understanding-undefined-value-returned-from-a-function
|
||||
|
||||
# --description--
|
||||
|
||||
A function can include the `return` statement but it does not have to. In the case that the function doesn't have a `return` statement, when you call it, the function processes the inner code but the returned value is `undefined`.
|
||||
Uma função pode incluir a instrução `return` mas ela não precisa fazer isso. No caso de a função não ter uma instrução `return`, quando você chamá-la, a função processa o código interno, mas o valor retornado é `undefined`.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
var sum = 0;
|
||||
@ -21,39 +21,38 @@ function addSum(num) {
|
||||
addSum(3);
|
||||
```
|
||||
|
||||
`addSum` is a function without a `return` statement. The function will change the global `sum` variable but the returned value of the function is `undefined`.
|
||||
`addSum` é uma função sem uma instrução `return`. A função irá alterar a variável global `sum`, mas o valor retornado da função é `undefined`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function `addFive` without any arguments. This function adds 5 to the `sum` variable, but its returned value is `undefined`.
|
||||
Crie uma função `addFive` sem qualquer argumento. Essa função adiciona 5 à variável</code>sum`, mas o valor retornado é <code>undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`addFive` should be a function.
|
||||
`addFive` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof addFive === 'function');
|
||||
```
|
||||
|
||||
Once both functions have run, the `sum` should be equal to `8`.
|
||||
Uma vez que ambas as funções são executadas, a `soma` deve ser igual a `8`.
|
||||
|
||||
```js
|
||||
assert(sum === 8);
|
||||
```
|
||||
|
||||
Returned value from `addFive` should be `undefined`.
|
||||
Valor retornado de `addFive` deve ser `undefined`.
|
||||
|
||||
```js
|
||||
assert(addFive() === undefined);
|
||||
```
|
||||
|
||||
Inside the `addFive` function, you should add `5` to the `sum` variable.
|
||||
Dentro da função `addFive`, você deve adicionar `5` à variável `sum<code>.</p>
|
||||
|
||||
```js
|
||||
assert(
|
||||
<pre><code class="js">assert(
|
||||
__helpers.removeWhiteSpace(addFive.toString()).match(/sum=sum\+5|sum\+=5/)
|
||||
);
|
||||
```
|
||||
`</pre>
|
||||
|
||||
# --seed--
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244aa
|
||||
title: Understanding Uninitialized Variables
|
||||
title: Entendendo Variáveis Não Inicializadas
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBa2JAL'
|
||||
forumTopicId: 18335
|
||||
@ -9,33 +9,33 @@ dashedName: understanding-uninitialized-variables
|
||||
|
||||
# --description--
|
||||
|
||||
When JavaScript variables are declared, they have an initial value of `undefined`. If you do a mathematical operation on an `undefined` variable your result will be `NaN` which means <dfn>"Not a Number"</dfn>. If you concatenate a string with an `undefined` variable, you will get a literal <dfn>string</dfn> of `undefined`.
|
||||
Quando as variáveis de JavaScript são declaradas, elas têm um valor inicial de `undefined`. Se você fizer uma operação matemática em uma variável `undefined`, seu resultado será `NaN`, o que significa que <dfn>"Não é um número"</dfn>. Se você concatenar uma string com uma variável `undefined`, você receberá uma string <dfn>literal</dfn> de `undefined`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Initialize the three variables `a`, `b`, and `c` with `5`, `10`, and `"I am a"` respectively so that they will not be `undefined`.
|
||||
Inicialize as três variáveis `a`, `b` e `c` com `5`, `10`, e `"Sou a"` respectivamente para que eles não sejam `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should be defined and evaluated to have the value of `6`.
|
||||
`a` deve ser definido e avaliado para ter o valor de `6`.
|
||||
|
||||
```js
|
||||
assert(typeof a === 'number' && a === 6);
|
||||
```
|
||||
|
||||
`b` should be defined and evaluated to have the value of `15`.
|
||||
`b` deve ser definido e avaliado para ter o valor de `15`.
|
||||
|
||||
```js
|
||||
assert(typeof b === 'number' && b === 15);
|
||||
```
|
||||
|
||||
`c` should not contain `undefined` and should have a value of the string `I am a String!`
|
||||
`c` não deve conter `undefined` e deve ter o valor da string `eu sou uma String!`
|
||||
|
||||
```js
|
||||
assert(!/undefined/.test(c) && c === 'I am a String!');
|
||||
```
|
||||
|
||||
You should not change code below the specified comment.
|
||||
Você não deve mudar o código abaixo do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d1
|
||||
title: Updating Object Properties
|
||||
title: Atualizando Propriedades do Objeto
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9yEJT4'
|
||||
forumTopicId: 18336
|
||||
@ -9,9 +9,9 @@ dashedName: updating-object-properties
|
||||
|
||||
# --description--
|
||||
|
||||
After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.
|
||||
Depois de criar um objeto JavaScript, você pode atualizar suas propriedades a qualquer momento, como você atualizaria qualquer outra variável. Você pode usar notação do ponto ou colchete para atualizar.
|
||||
|
||||
For example, let's look at `ourDog`:
|
||||
Por exemplo, vamos dar uma olhada em `ourDog`:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
@ -22,21 +22,21 @@ var ourDog = {
|
||||
};
|
||||
```
|
||||
|
||||
Since he's a particularly happy dog, let's change his name to the string `Happy Camper`. Here's how we update his object's name property: `ourDog.name = "Happy Camper";` or `ourDog["name"] = "Happy Camper";` Now when we evaluate `ourDog.name`, instead of getting `Camper`, we'll get his new name, `Happy Camper`.
|
||||
Como ele é um cachorro particularmente feliz, vamos mudar seu nome para o texto `Happy Camper`. Veja como atualizamos a propriedade name do objeto: `ourDog.name = "Happy Camper";` ou `ourDog["name"] = "Happy Camper";` Agora, quando avaliamos `ourDog.name`, em vez de obter `Camper`, teremos seu novo nome, `Happy Camper`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Update the `myDog` object's name property. Let's change her name from `Coder` to `Happy Coder`. You can use either dot or bracket notation.
|
||||
Atualize a propriedade name do objeto `myDog`. Vamos alterar o valor da propriedade name dela de `Coder` para `Happy Coder`. Você pode usar notação de ponto ou de colchetes.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should update `myDog`'s `name` property to equal the string `Happy Coder`.
|
||||
Você deve atualizar a propriedade `name` de `myDog` para ser igual a `Happy Coder`.
|
||||
|
||||
```js
|
||||
assert(/happy coder/gi.test(myDog.name));
|
||||
```
|
||||
|
||||
You should not edit the `myDog` definition.
|
||||
Você não deve editar a definição de `myDog`.
|
||||
|
||||
```js
|
||||
assert(/"name": "Coder"/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c549eddfaeb5bdef
|
||||
title: Use Bracket Notation to Find the First Character in a String
|
||||
title: Use Notação de Colchetes para Encontrar o Primeiro Caractere em uma String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8JwhW'
|
||||
forumTopicId: 18341
|
||||
@ -9,36 +9,36 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Bracket notation</dfn> is a way to get a character at a specific index within a string.
|
||||
<dfn>Notação de Colchetes</dfn> é uma forma de pegar um caractere no índice especificado dentro de uma string.
|
||||
|
||||
Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as <dfn>Zero-based</dfn> indexing.
|
||||
A maioria das linguagens de programações modernas, como JavaScript, não começa contando do 1 como humanos fazem. Eles começam no 0. Isso é referido como indexação <dfn>baseada em zero</dfn>.
|
||||
|
||||
For example, the character at index 0 in the word `Charles` is `C`. So if `var firstName = "Charles"`, you can get the value of the first letter of the string by using `firstName[0]`.
|
||||
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]`.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var firstName = "Charles";
|
||||
var firstLetter = firstName[0];
|
||||
```
|
||||
|
||||
`firstLetter` would have a value of the string `C`.
|
||||
`firstLetter` teria o valor da string `C`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use bracket notation to find the first character in the `lastName` variable and assign it to `firstLetterOfLastName`.
|
||||
Use notação de colchetes para encontrar o primeiro caractere na variável `lastName` e atribua a letra para a variável `firstLetterOfLastName`.
|
||||
|
||||
**Hint:** Try looking at the example above if you get stuck.
|
||||
**Dica:** Tente olhar o exemplo acima se você ficar travado.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `firstLetterOfLastName` variable should have the value of `L`.
|
||||
A variável `firstLetterOfLastName` deve ter o valor de `L`.
|
||||
|
||||
```js
|
||||
assert(firstLetterOfLastName === 'L');
|
||||
```
|
||||
|
||||
You should use bracket notation.
|
||||
Você deve usar a notação de colchetes.
|
||||
|
||||
```js
|
||||
assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c451eddfaeb5bdef
|
||||
title: Use Bracket Notation to Find the Last Character in a String
|
||||
title: Use Notação de Colchetes para Encontrar o Último Caractere em uma String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZQGcv'
|
||||
forumTopicId: 18342
|
||||
@ -9,34 +9,34 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
In order to get the last letter of a string, you can subtract one from the string's length.
|
||||
Em ordem para pegar a última letra de uma string, você pode subtrair um do tamanho da string.
|
||||
|
||||
For example, if `var firstName = "Ada"`, you can get the value of the last letter of the string by using `firstName[firstName.length - 1]`.
|
||||
Por exemplo, se `var firstName = "Ada"`, você pode pegar o valor da última letra da string ao usar `firstName[firstName.length - 1]`.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var firstName = "Ada";
|
||||
var lastLetter = firstName[firstName.length - 1];
|
||||
```
|
||||
|
||||
`lastLetter` would have a value of the string `a`.
|
||||
`lastLetter` teria o valor da string `a`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use <dfn>bracket notation</dfn> to find the last character in the `lastName` variable.
|
||||
Use <dfn>notação de colchetes</dfn> para descobrir o último caracter na variável `lastName`.
|
||||
|
||||
**Hint:** Try looking at the example above if you get stuck.
|
||||
**Dica:** Tente olhar o exemplo acima se você ficar travado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lastLetterOfLastName` should be the letter `e`.
|
||||
`lastLetterOfLastName` deve ser a letra `e`.
|
||||
|
||||
```js
|
||||
assert(lastLetterOfLastName === 'e');
|
||||
```
|
||||
|
||||
You should use `.length` to get the last letter.
|
||||
Você deve usar `.length` para pegar a última letra.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.length/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c450eddfaeb5bdef
|
||||
title: Use Bracket Notation to Find the Nth Character in a String
|
||||
title: Use Notação de Colchetes para Encontrar o Nº Caractere em uma String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWPVJua'
|
||||
forumTopicId: 18343
|
||||
@ -9,34 +9,34 @@ dashedName: use-bracket-notation-to-find-the-nth-character-in-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
You can also use <dfn>bracket notation</dfn> to get the character at other positions within a string.
|
||||
Você também pode usar <dfn>notação de colchetes</dfn> para pegar caracteres em outras posições em uma string.
|
||||
|
||||
Remember that computers start counting at `0`, so the first character is actually the zeroth character.
|
||||
Lembre-se que computadores começam contando do `0`, então o primeiro caractere é na verdade o caractere na posição 0.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var firstName = "Ada";
|
||||
var secondLetterOfFirstName = firstName[1];
|
||||
```
|
||||
|
||||
`secondLetterOfFirstName` would have a value of the string `d`.
|
||||
`secondLetterOfFirstName` teria o valor da string `d`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Let's try to set `thirdLetterOfLastName` to equal the third letter of the `lastName` variable using bracket notation.
|
||||
Vamos tentar definir `thirdLetterOfLastName` para ser igual a terceira letra da variável `lastName` usando notação de colchetes.
|
||||
|
||||
**Hint:** Try looking at the example above if you get stuck.
|
||||
**Dica:** Tente olhar o exemplo acima se você ficar travado.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `thirdLetterOfLastName` variable should have the value of `v`.
|
||||
A variável `thirdLetterOfLastName` deve ter o valor de `v`.
|
||||
|
||||
```js
|
||||
assert(thirdLetterOfLastName === 'v');
|
||||
```
|
||||
|
||||
You should use bracket notation.
|
||||
Você deve usar notação de colchetes.
|
||||
|
||||
```js
|
||||
assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c452eddfaeb5bdef
|
||||
title: Use Bracket Notation to Find the Nth-to-Last Character in a String
|
||||
title: Use Notação de Colchetes para Descobrir o Nº Antes do Ultimo em uma String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cw4vkh9'
|
||||
forumTopicId: 18344
|
||||
@ -9,34 +9,34 @@ dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.
|
||||
Você pode usar o mesmo princípio que nós acabamos de usar para recuperar o último caractere em uma string, para recuperar o Nº antes do último caractere.
|
||||
|
||||
For example, you can get the value of the third-to-last letter of the `var firstName = "Augusta"` string by using `firstName[firstName.length - 3]`
|
||||
Por exemplo, você pode pegar o valor da antepenúltima letra da string `var fistName = "Augusta` usando `firstName[firstName.length -3]`
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var firstName = "Augusta";
|
||||
var thirdToLastLetter = firstName[firstName.length - 3];
|
||||
```
|
||||
|
||||
`thirdToLastLetter` would have a value of the string `s`.
|
||||
`thirdToLastLetter` teria o valor da string `s`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use <dfn>bracket notation</dfn> to find the second-to-last character in the `lastName` string.
|
||||
Use <dfn>notação de colchetes</dfn> para descobrir o penúltimo caractere na string `lastName`.
|
||||
|
||||
**Hint:** Try looking at the example above if you get stuck.
|
||||
**Dica:** Tente olhar o exemplo acima se você ficar travado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`secondToLastLetterOfLastName` should be the letter `c`.
|
||||
`secondToLastLetterOfLastName` deve ser a letra `c`.
|
||||
|
||||
```js
|
||||
assert(secondToLastLetterOfLastName === 'c');
|
||||
```
|
||||
|
||||
You should use `.length` to get the second last letter.
|
||||
Você deve usar `.length` para pegar a penúltima letra.
|
||||
|
||||
```js
|
||||
assert(code.match(/\.length/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb3bdef
|
||||
title: Use Conditional Logic with If Statements
|
||||
title: Use Lógica Condicional com Instruções If
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87mf3'
|
||||
forumTopicId: 18348
|
||||
@ -9,15 +9,15 @@ dashedName: use-conditional-logic-with-if-statements
|
||||
|
||||
# --description--
|
||||
|
||||
`If` statements are used to make decisions in code. The keyword `if` tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as `Boolean` conditions and they may only be `true` or `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`.
|
||||
|
||||
When the condition evaluates to `true`, the program executes the statement inside the curly braces. When the Boolean condition evaluates to `false`, the statement inside the curly braces will not execute.
|
||||
Quando a condição for `true`, o programa executara as instruções dentro das chaves. Quando a condição booleana for `false`, as instruções dentro das chaves não serão executadas.
|
||||
|
||||
**Pseudocode**
|
||||
**Pseudocódigo**
|
||||
|
||||
<blockquote>if (<i>condition is true</i>) {<br> <i>statement is executed</i><br>}</blockquote>
|
||||
<blockquote>if (<i>condição é verdadeira</i>) {<br><i>instrução é executada</i><br>}</blockquote>
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
function test (myCondition) {
|
||||
@ -30,41 +30,41 @@ test(true);
|
||||
test(false);
|
||||
```
|
||||
|
||||
`test(true)` returns the string `It was true`, and `test(false)` returns the string `It was false`.
|
||||
`test(true)` retorna a string `It was true` e `test(false)` retorna a string `It was false`.
|
||||
|
||||
When `test` is called with a value of `true`, the `if` statement evaluates `myCondition` to see if it is `true` or not. Since it is `true`, the function returns `It was true`. When we call `test` with a value of `false`, `myCondition` is *not* `true` and the statement in the curly braces is not executed and the function returns `It was false`.
|
||||
Quando `test` é chamado com o valor `true`, a instrução `if` avalia `myCondition` para verificar se é `true` ou não. Já que é `true`, a função retorna `It was true`. Quando chamamos `test` com um valor de `false`, `myCondition` *não é* `true` e a instrução nas chaves não é executada e a função retorna `It was false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create an `if` statement inside the function to return `Yes, that was true` if the parameter `wasThatTrue` is `true` and return `No, that was false` otherwise.
|
||||
Crie uma instrução `if` dentro da função para retornar `Yes, that was true` se o parâmetro `wasThatTrue` for `true` e retorne `No, that was false` caso contrário.
|
||||
|
||||
# --hints--
|
||||
|
||||
`trueOrFalse` should be a function
|
||||
`trueOrFalse` deve ser uma função
|
||||
|
||||
```js
|
||||
assert(typeof trueOrFalse === 'function');
|
||||
```
|
||||
|
||||
`trueOrFalse(true)` should return a string
|
||||
`trueOrFalse(true)` deve retornar uma string
|
||||
|
||||
```js
|
||||
assert(typeof trueOrFalse(true) === 'string');
|
||||
```
|
||||
|
||||
`trueOrFalse(false)` should return a string
|
||||
`trueOrFalse(false)` deve retornar uma string
|
||||
|
||||
```js
|
||||
assert(typeof trueOrFalse(false) === 'string');
|
||||
```
|
||||
|
||||
`trueOrFalse(true)` should return the string `Yes, that was true`
|
||||
`trueOrFalse(true)` deve retornar a string `Yes, that was true`
|
||||
|
||||
```js
|
||||
assert(trueOrFalse(true) === 'Yes, that was true');
|
||||
```
|
||||
|
||||
`trueOrFalse(false)` should return the string `No, that was false`
|
||||
`trueOrFalse(false)` deve retornar a string `No, that was false`
|
||||
|
||||
```js
|
||||
assert(trueOrFalse(false) === 'No, that was false');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b21
|
||||
title: Use Multiple Conditional (Ternary) Operators
|
||||
title: Usar Operadores de Múltiplas Condições (Ternário)
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cyWJBT4'
|
||||
forumTopicId: 301179
|
||||
@ -9,9 +9,9 @@ dashedName: use-multiple-conditional-ternary-operators
|
||||
|
||||
# --description--
|
||||
|
||||
In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions.
|
||||
No desafio anterior, você usou um único operador condicional. Você também pode encadear eles juntos para verificar por múltiplas condições.
|
||||
|
||||
The following function uses `if`, `else if`, and `else` statements to check multiple conditions:
|
||||
A seguinte função usa as instruções `if`, `else if` e `else` para verificar múltiplas condições:
|
||||
|
||||
```js
|
||||
function findGreaterOrEqual(a, b) {
|
||||
@ -27,7 +27,7 @@ function findGreaterOrEqual(a, b) {
|
||||
}
|
||||
```
|
||||
|
||||
The above function can be re-written using multiple conditional operators:
|
||||
A função acima pode ser rescrita usando operadores de múltiplas condições (operador ternário):
|
||||
|
||||
```js
|
||||
function findGreaterOrEqual(a, b) {
|
||||
@ -37,7 +37,7 @@ function findGreaterOrEqual(a, b) {
|
||||
}
|
||||
```
|
||||
|
||||
It is considered best practice to format multiple conditional operators such that each condition is on a separate line, as shown above. Using multiple conditional operators without proper indentation may make your code hard to read. For example:
|
||||
É considerado a melhor prática para formatar operadores de múltiplas condições, tal que cada condição está em uma linha separada, como mostrada acima. Usando operadores de múltiplas condições sem a indentação adequada pode dificultar a leitura do seu código. Por exemplo:
|
||||
|
||||
```js
|
||||
function findGreaterOrEqual(a, b) {
|
||||
@ -47,29 +47,29 @@ function findGreaterOrEqual(a, b) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
In the `checkSign` function, use multiple conditional operators - following the recommended format used in `findGreaterOrEqual` - to check if a number is positive, negative or zero. The function should return `positive`, `negative` or `zero`.
|
||||
Na função `checkSign`, use operadores de múltiplas condições - seguindo o formato recomendado usado em `findGreaterOrEqual` - para verificar se um número é positivo, negativo ou zero. A função deve retornar `positive`, `negative` ou `zero`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkSign` should use multiple conditional operators
|
||||
`checkSign` deve usar operadores de múltiplas condições
|
||||
|
||||
```js
|
||||
assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code));
|
||||
```
|
||||
|
||||
`checkSign(10)` should return the string `positive`. Note that capitalization matters
|
||||
`checkSign(10)` deve retornar a string `positive`. Observe que a capitalização importa
|
||||
|
||||
```js
|
||||
assert(checkSign(10) === 'positive');
|
||||
```
|
||||
|
||||
`checkSign(-12)` should return the string `negative`. Note that capitalization matters
|
||||
`checkSign(-12)` deve retornar a string `negative`. Observe que a capitalização importa
|
||||
|
||||
```js
|
||||
assert(checkSign(-12) === 'negative');
|
||||
```
|
||||
|
||||
`checkSign(0)` should return the string `zero`. Note that capitalization matters
|
||||
`checkSign(0)` deve retornar a string `zero`. Observe que a capitalização importa
|
||||
|
||||
```js
|
||||
assert(checkSign(0) === 'zero');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cd9a70215d3c4e65518328f
|
||||
title: Use Recursion to Create a Countdown
|
||||
title: Use Recursividade para Criar uma Contagem Regressiva
|
||||
challengeType: 1
|
||||
forumTopicId: 305925
|
||||
dashedName: use-recursion-to-create-a-countdown
|
||||
@ -8,11 +8,11 @@ dashedName: use-recursion-to-create-a-countdown
|
||||
|
||||
# --description--
|
||||
|
||||
In a [previous challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion), you learned how to use recursion to replace a `for` loop. Now, let's look at a more complex function that returns an array of consecutive integers starting with `1` through the number passed to the function.
|
||||
Em um [desafio anterior](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion), você aprendeu como usar recursividade para substituir laços `for`. Agora, vamos analisar uma função mais complexa, a qual retorna um array de inteiros consecutivos começando com `1` até o número passado para a função.
|
||||
|
||||
As mentioned in the previous challenge, there will be a <dfn>base case</dfn>. The base case tells the recursive function when it no longer needs to call itself. It is a simple case where the return value is already known. There will also be a <dfn>recursive call</dfn> which executes the original function with different arguments. If the function is written correctly, eventually the base case will be reached.
|
||||
Como mencionado no desafio anterior, haverá um <dfn>caso base</dfn>. O caso base diz a função recursiva quando ela não precisa mais chamar a si. É um simples caso onde o valor de retorno já é conhecido. Também haverá uma <dfn>chamada recursiva</dfn> a qual executa a função original com argumentos diferentes. Se a função for escrita corretamente, eventualmente o caso base será alcançado.
|
||||
|
||||
For example, say you want to write a recursive function that returns an array containing the numbers `1` through `n`. This function will need to accept an argument, `n`, representing the final number. Then it will need to call itself with progressively smaller values of `n` until it reaches `1`. You could write the function as follows:
|
||||
Por exemplo, vamos dizer que você quer escrever uma função recursiva que retorna um array contendo os números de `1` até `n`. Essa função precisará aceitar um argumento, `n`, representando o número final. Então ela precisará chamar a si mesmo como valores progressivamente menores de `n` até que alcance `1`. Você poderia escrever a função da seguinte forma:
|
||||
|
||||
```javascript
|
||||
function countup(n) {
|
||||
@ -27,35 +27,35 @@ function countup(n) {
|
||||
console.log(countup(5));
|
||||
```
|
||||
|
||||
The value `[1, 2, 3, 4, 5]` will be displayed in the console.
|
||||
O valor `[1, 2, 3, 4, 5]` será exibido no console.
|
||||
|
||||
At first, this seems counterintuitive since the value of `n` *decreases*, but the values in the final array are *increasing*. This happens because the push happens last, after the recursive call has returned. At the point where `n` is pushed into the array, `countup(n - 1)` has already been evaluated and returned `[1, 2, ..., n - 1]`.
|
||||
Inicialmente, isso se parece contra-intuitivo já que o valor de `n` *diminui*, mas os valores no array final estão *em ordem crescente*. Isso acontece porque a adição no array (push) acontece por último, após a chamada recursiva ter retornado. No ponto onde `n` é adicionado ao array, `countup(n - 1)` já foi avaliado e retornou `[1, 2, ..., n -1]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function called `countdown` with one parameter (`n`). The function should use recursion to return an array containing the integers `n` through `1` based on the `n` parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function with `n = 5` should return the array `[5, 4, 3, 2, 1]`. Your function must use recursion by calling itself and must not use loops of any kind.
|
||||
Definimos uma função chamada `countdown` com um parâmetro (`n`). A função deve usar recursividade para retornar um array contendo inteiros `n` até `1` baseado no parâmetro `n`. Se a função é chamada com um número menor que 1, a função deve retornar um array vazio. Por exemplo, chamando essa função com `n = 5` deve retornar o array `[5, 4, 3, 2, 1]`. Sua função precisa usar recursividade ao chamar ela mesma e não deve usar laços de qualquer tipo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`countdown(-1)` should return an empty array.
|
||||
`countdown(-1)` deve retornar um array vazio.
|
||||
|
||||
```js
|
||||
assert.isEmpty(countdown(-1));
|
||||
```
|
||||
|
||||
`countdown(10)` should return `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`
|
||||
`countdown(10)` deve retornar `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(countdown(10), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
|
||||
```
|
||||
|
||||
`countdown(5)` should return `[5, 4, 3, 2, 1]`
|
||||
`countdown(5)` deve retornar `[5, 4, 3, 2, 1]`
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(countdown(5), [5, 4, 3, 2, 1]);
|
||||
```
|
||||
|
||||
Your code should not rely on any kind of loops (`for`, `while` or higher order functions such as `forEach`, `map`, `filter`, and `reduce`).
|
||||
Seu código não deve depender de nenhum tipo de laço (`for`, `while` ou outras funções superiores como `forEach`, `map`, `filter` e `reduce`).
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -63,7 +63,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use recursion to solve this problem.
|
||||
Você deve usar recursividade para resolver esse problema.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cc0bd7a49b71cb96132e54c
|
||||
title: Use Recursion to Create a Range of Numbers
|
||||
title: Use Recursividade para Criar um Intervalo de Números
|
||||
challengeType: 1
|
||||
forumTopicId: 301180
|
||||
dashedName: use-recursion-to-create-a-range-of-numbers
|
||||
@ -8,21 +8,21 @@ dashedName: use-recursion-to-create-a-range-of-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
Continuing from the previous challenge, we provide you another opportunity to create a recursive function to solve a problem.
|
||||
Continuando do desafio anterior, nós o fornecemos outra oportunidade para criar uma função recursiva para resolver um problema.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function named `rangeOfNumbers` with two parameters. The function should return an array of integers which begins with a number represented by the `startNum` parameter and ends with a number represented by the `endNum` parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both `startNum` and `endNum` are the same.
|
||||
Definimos uma função chamada `rangeOfNumbers` com dois parâmetros. A função deve retornar um array de inteiros a qual começa com um número representado pelo parâmetro `startNum` e terminar com um número representado pelo parâmetro `endNum`. O número inicial sempre será menor ou igual ao número final. Sua função precisa usar recursividade ao chamar ela mesma e não depender de nenhum tipo de laço. Também deve funcionar para casos onde ambos `startNum` e `endNum` forem o mesmo.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your function should return an array.
|
||||
Sua função deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(rangeOfNumbers(5, 10)));
|
||||
```
|
||||
|
||||
Your code should not use any loop syntax (`for` or `while` or higher order functions such as `forEach`, `map`, `filter`, or `reduce`).
|
||||
Seu código não deve depender de nenhum laço (`for` ou `while` ou funções de ordem superior como as funções `forEach`, `map`, `filter` ou `reduce`).
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`rangeOfNumbers` should use recursion (call itself) to solve this challenge.
|
||||
`rangeOfNumbers` deve usar recursão (chamar a si) para resolver este desafio.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,19 +38,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`rangeOfNumbers(1, 5)` should return `[1, 2, 3, 4, 5]`.
|
||||
`rangeOfNumbers(1, 5)` deve retornar `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(rangeOfNumbers(1, 5), [1, 2, 3, 4, 5]);
|
||||
```
|
||||
|
||||
`rangeOfNumbers(6, 9)` should return `[6, 7, 8, 9]`.
|
||||
`rangeOfNumbers(6, 9)` deve retornar `[6, 7, 8, 9]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(rangeOfNumbers(6, 9), [6, 7, 8, 9]);
|
||||
```
|
||||
|
||||
`rangeOfNumbers(4, 4)` should return `[4]`.
|
||||
`rangeOfNumbers(4, 4)` deve retornar `[4]`.
|
||||
|
||||
```js
|
||||
assert.deepStrictEqual(rangeOfNumbers(4, 4), [4]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b24
|
||||
title: Use the Conditional (Ternary) Operator
|
||||
title: Use o Operador Condicional (ternário)
|
||||
challengeType: 1
|
||||
forumTopicId: 301181
|
||||
dashedName: use-the-conditional-ternary-operator
|
||||
@ -8,11 +8,11 @@ dashedName: use-the-conditional-ternary-operator
|
||||
|
||||
# --description--
|
||||
|
||||
The <dfn>conditional operator</dfn>, also called the <dfn>ternary operator</dfn>, can be used as a one line if-else expression.
|
||||
O <dfn>operador condicional</dfn>, também chamado de <dfn>operador ternário</dfn>, pode ser usado como uma expressão if-else de uma linha.
|
||||
|
||||
The syntax is `a ? b : c`, where `a` is the condition, `b` is the code to run when the condition returns `true`, and `c` is the code to run when the condition returns `false`.
|
||||
A sintaxe é `a ? b : c`, onde `a` é a condição, `b` é o código executado quando a condição retorna `true` e `c` é o código executado quando a condição retorna `false`.
|
||||
|
||||
The following function uses an `if/else` statement to check a condition:
|
||||
A função a seguir usa a instrução `if/else` para verificar uma condição:
|
||||
|
||||
```js
|
||||
function findGreater(a, b) {
|
||||
@ -25,7 +25,7 @@ function findGreater(a, b) {
|
||||
}
|
||||
```
|
||||
|
||||
This can be re-written using the conditional operator:
|
||||
Isto pode ser reescrito usando o operador condicional:
|
||||
|
||||
```js
|
||||
function findGreater(a, b) {
|
||||
@ -35,29 +35,29 @@ function findGreater(a, b) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the conditional operator in the `checkEqual` function to check if two numbers are equal or not. The function should return either the string `Equal` or the string `Not Equal`.
|
||||
Use o operador condicional na função `checkEqual` para verificar se dois números são iguais ou não. A função deve retornar ou a string `Equal` ou a string `Not Equal`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkEqual` should use the conditional operator
|
||||
`checkEqual` deve usar o operador condicional
|
||||
|
||||
```js
|
||||
assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code));
|
||||
```
|
||||
|
||||
`checkEqual(1, 2)` should return the string `Not Equal`
|
||||
`checkEqual(1, 2)` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(checkEqual(1, 2) === 'Not Equal');
|
||||
```
|
||||
|
||||
`checkEqual(1, 1)` should return the string `Equal`
|
||||
`checkEqual(1, 1)` deve retornar a string `Equal`
|
||||
|
||||
```js
|
||||
assert(checkEqual(1, 1) === 'Equal');
|
||||
```
|
||||
|
||||
`checkEqual(1, -1)` should return the string `Not Equal`
|
||||
`checkEqual(1, -1)` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(checkEqual(1, -1) === 'Not Equal');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b22
|
||||
title: Use the parseInt Function with a Radix
|
||||
title: Use a Função parseInt com um Radix
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6K4Kh3'
|
||||
forumTopicId: 301182
|
||||
@ -9,53 +9,53 @@ dashedName: use-the-parseint-function-with-a-radix
|
||||
|
||||
# --description--
|
||||
|
||||
The `parseInt()` function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36.
|
||||
A função `parseInt()` analisa uma string e retorna um inteiro. É preciso um segundo argumento para o radix, que especifica a base do número na string. O radix pode ser um inteiro entre 2 e 36.
|
||||
|
||||
The function call looks like:
|
||||
A chamada da função se parece com:
|
||||
|
||||
```js
|
||||
parseInt(string, radix);
|
||||
```
|
||||
|
||||
And here's an example:
|
||||
E aqui um exemplo:
|
||||
|
||||
```js
|
||||
var a = parseInt("11", 2);
|
||||
```
|
||||
|
||||
The radix variable says that `11` is in the binary system, or base 2. This example converts the string `11` to an integer `3`.
|
||||
A variável radix diz que `11` está no sistema binário, ou base 2. Esse exemplo converte a string `11` para um inteiro `3`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use `parseInt()` in the `convertToInteger` function so it converts a binary number to an integer and returns it.
|
||||
Use `parseInt()` na função `convertToInteger` para que ela converta um número binário em um inteiro e o retorne.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertToInteger` should use the `parseInt()` function
|
||||
`convertToInteger` deve usar a função `parseInt()`
|
||||
|
||||
```js
|
||||
assert(/parseInt/g.test(code));
|
||||
```
|
||||
|
||||
`convertToInteger("10011")` should return a number
|
||||
`convertToInteger("10011")` deve retornar um número
|
||||
|
||||
```js
|
||||
assert(typeof convertToInteger('10011') === 'number');
|
||||
```
|
||||
|
||||
`convertToInteger("10011")` should return 19
|
||||
`convertToInteger("10011")` deve retornar 19
|
||||
|
||||
```js
|
||||
assert(convertToInteger('10011') === 19);
|
||||
```
|
||||
|
||||
`convertToInteger("111001")` should return 57
|
||||
`convertToInteger("111001")` deve retornar 57
|
||||
|
||||
```js
|
||||
assert(convertToInteger('111001') === 57);
|
||||
```
|
||||
|
||||
`convertToInteger("JamesBond")` should return `NaN`
|
||||
`convertToInteger("JamesBond")` deve retornar `NaN`
|
||||
|
||||
```js
|
||||
assert.isNaN(convertToInteger('JamesBond'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b23
|
||||
title: Use the parseInt Function
|
||||
title: Use a função parseInt
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm83LSW'
|
||||
forumTopicId: 301183
|
||||
@ -9,45 +9,45 @@ dashedName: use-the-parseint-function
|
||||
|
||||
# --description--
|
||||
|
||||
The `parseInt()` function parses a string and returns an integer. Here's an example:
|
||||
A função `parseInt()` analisa uma string e retorna um inteiro. Aqui está um exemplo:
|
||||
|
||||
```js
|
||||
var a = parseInt("007");
|
||||
```
|
||||
|
||||
The above function converts the string `007` to the integer `7`. If the first character in the string can't be converted into a number, then it returns `NaN`.
|
||||
A função acima converte a string `007` para o inteiro `7`. Se o primeiro caractere na string não pode ser convertido em um número, então ele retorna `NaN`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use `parseInt()` in the `convertToInteger` function so it converts the input string `str` into an integer, and returns it.
|
||||
Use `parseInt()` na função `convertToInteger` para que ela converta a string de entrada `str` em um inteiro e a retorne.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertToInteger` should use the `parseInt()` function
|
||||
`convertToInteger` deve usar a função `parseInt()`
|
||||
|
||||
```js
|
||||
assert(/parseInt/g.test(code));
|
||||
```
|
||||
|
||||
`convertToInteger("56")` should return a number
|
||||
`convertToInteger("56")` deve retornar um número
|
||||
|
||||
```js
|
||||
assert(typeof convertToInteger('56') === 'number');
|
||||
```
|
||||
|
||||
`convertToInteger("56")` should return 56
|
||||
`convertToInteger("56")` deve retornar 56
|
||||
|
||||
```js
|
||||
assert(convertToInteger('56') === 56);
|
||||
```
|
||||
|
||||
`convertToInteger("77")` should return 77
|
||||
`convertToInteger("77")` deve retornar 77
|
||||
|
||||
```js
|
||||
assert(convertToInteger('77') === 77);
|
||||
```
|
||||
|
||||
`convertToInteger("JamesBond")` should return `NaN`
|
||||
`convertToInteger("JamesBond")` deve retornar `NaN`
|
||||
|
||||
```js
|
||||
assert.isNaN(convertToInteger('JamesBond'));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ca
|
||||
title: Using Objects for Lookups
|
||||
title: Usando Objetos para Pesquisas
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBk8sM'
|
||||
forumTopicId: 18373
|
||||
@ -9,9 +9,9 @@ dashedName: using-objects-for-lookups
|
||||
|
||||
# --description--
|
||||
|
||||
Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to lookup values rather than a `switch` statement or an `if/else` chain. This is most useful when you know that your input data is limited to a certain range.
|
||||
Objetos podem ser pensados como armazenamento de chave/valor, como um dicionário. Se você tem um dado tabular, você pode usar um objeto para pesquisar valores ao invés de uma instrução `switch` ou uma cadeia de `if/else`. Isso é mais útil quando você sabe que o seu dado de entrada é limitado para um certo intervalo.
|
||||
|
||||
Here is an example of a simple reverse alphabet lookup:
|
||||
Aqui está um exemplo de uma simples pesquisa reversa no alfabeto:
|
||||
|
||||
```js
|
||||
var alpha = {
|
||||
@ -31,63 +31,63 @@ var value = 2;
|
||||
alpha[value];
|
||||
```
|
||||
|
||||
`alpha[2]` is the string `Y`, `alpha[24]` is the string `C`, and `alpha[value]` is the string `Y`.
|
||||
`alpha[2]` é a string `Y`, `alpha[24]` é a string `C` e `alpha[value]` é a string `Y`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the switch statement into an object called `lookup`. Use it to look up `val` and assign the associated string to the `result` variable.
|
||||
Converta a instrução switch em um objeto chamado `lookup`. Use ele para pesquisar por `val` e atribua a string associada para a variável `result`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`phoneticLookup("alpha")` should equal the string `Adams`
|
||||
`phoneticLookup("alpha")` deve ser igual a string `Adams`
|
||||
|
||||
```js
|
||||
assert(phoneticLookup('alpha') === 'Adams');
|
||||
```
|
||||
|
||||
`phoneticLookup("bravo")` should equal the string `Boston`
|
||||
`phoneticLookup("bravo")` deve ser igual a string `Boston`
|
||||
|
||||
```js
|
||||
assert(phoneticLookup('bravo') === 'Boston');
|
||||
```
|
||||
|
||||
`phoneticLookup("charlie")` should equal the string `Chicago`
|
||||
`phoneticLookup("charlie")` deve ser igual a string `Chicago`
|
||||
|
||||
```js
|
||||
assert(phoneticLookup('charlie') === 'Chicago');
|
||||
```
|
||||
|
||||
`phoneticLookup("delta")` should equal the string `Denver`
|
||||
`phoneticLookup("delta")` deve ser igual a string `Denver`
|
||||
|
||||
```js
|
||||
assert(phoneticLookup('delta') === 'Denver');
|
||||
```
|
||||
|
||||
`phoneticLookup("echo")` should equal the string `Easy`
|
||||
`phoneticLookup("echo")` deve ser igual a string `Easy`
|
||||
|
||||
```js
|
||||
assert(phoneticLookup('echo') === 'Easy');
|
||||
```
|
||||
|
||||
`phoneticLookup("foxtrot")` should equal the string `Frank`
|
||||
`phoneticLookup("foxtrot")` deve ser igual a string `Frank`
|
||||
|
||||
```js
|
||||
assert(phoneticLookup('foxtrot') === 'Frank');
|
||||
```
|
||||
|
||||
`phoneticLookup("")` should equal `undefined`
|
||||
`phoneticLookup("")` deve ser igual a `undefined`
|
||||
|
||||
```js
|
||||
assert(typeof phoneticLookup('') === 'undefined');
|
||||
```
|
||||
|
||||
You should not modify the `return` statement
|
||||
Você não deve modificar a instrução `return`
|
||||
|
||||
```js
|
||||
assert(code.match(/return\sresult;/));
|
||||
```
|
||||
|
||||
You should not use `case`, `switch`, or `if` statements
|
||||
Você não deve usar as instruções `case`, `switch` ou `if`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -9,11 +9,11 @@ dashedName: word-blanks
|
||||
|
||||
# --description--
|
||||
|
||||
We will now use our knowledge of strings to build a "[Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)" style word game we're calling "Word Blanks". You will create an (optionally humorous) "Fill in the Blanks" style sentence.
|
||||
Nós iremos agora usar nosso conhecimento de strings para criar um "[Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)" estilo de jogo de palavras que chamamos de "Palavras em Branco". Você irá criar uma frase no estilo "Preencha os Espaços em Branco" (opcionalmente humorosa).
|
||||
|
||||
In a "Mad Libs" game, you are provided sentences with some missing words, like nouns, verbs, adjectives and adverbs. You then fill in the missing pieces with words of your choice in a way that the completed sentence makes sense.
|
||||
Em um jogo "Mad Libs", você recebe frases com algumas palavras faltando, como substantivos, verbos, adjetivos e advérbios. Você então irá preencher os pedaços faltantes com palavras de sua escolha em uma forma que a frase completa faça sentido.
|
||||
|
||||
Consider this sentence - It was really **\_\_\_\_**, and we **\_\_\_\_** ourselves **\_\_\_\_**. This sentence has three missing pieces- an adjective, a verb and an adverb, and we can add words of our choice to complete it. We can then assign the completed sentence to a variable as follows:
|
||||
Considere a frase - Era realmente **\_\_\_\_** e nós **\_\_\_\_** nós mesmos **\_\_\_\_**. Essa sentença possui três pedaços faltando - um adjetivo, um verbo e um advérbio, e nós podemos adicionar palavras de nossa escolha para completar. Em seguida, podemos atribuir a frase completa para uma variável como se segue:
|
||||
|
||||
```js
|
||||
var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";
|
||||
@ -21,21 +21,21 @@ var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves
|
||||
|
||||
# --instructions--
|
||||
|
||||
In this challenge, we provide you with a noun, a verb, an adjective and an adverb. You need to form a complete sentence using words of your choice, along with the words we provide.
|
||||
Nesse desafio, nós fornecemos a você um substantivo, um verbo, um adjetivo e um advérbio. Você precisar formular uma frase completa usando palavras de sua escolha, junto com as palavras que nós fornecemos.
|
||||
|
||||
You will need to use the string concatenation operator `+` to build a new string, using the provided variables: `myNoun`, `myAdjective`, `myVerb`, and `myAdverb`. You will then assign the formed string to the `wordBlanks` variable. You should not change the words assigned to the variables.
|
||||
Você precisará usar o operador de concatenação de string `+` para criar uma nova string, usando as variáveis fornecidas: `myNoun`, `myAdjective`, `myVerb` e `myAdverb`. Em seguida, você atribuirá a string formada para a variável `wordBlanks`. Você não deve alterar as palavras atribuídas às variáveis.
|
||||
|
||||
You will also need to account for spaces in your string, so that the final sentence has spaces between all the words. The result should be a complete sentence.
|
||||
Você também precisará se responsabilizar por espaços em sua string, para que na frase final possua espaços entre todas as palavras. O resultado não deve ser uma frase completa.
|
||||
|
||||
# --hints--
|
||||
|
||||
`wordBlanks` should be a string.
|
||||
`wordBlanks` deve ser uma string.
|
||||
|
||||
```js
|
||||
assert(typeof wordBlanks === 'string');
|
||||
```
|
||||
|
||||
You should not change the values assigned to `myNoun`, `myVerb`, `myAdjective` or `myAdverb`.
|
||||
Você não deve alterar os valores atribuídos a `myNoun`, `myVerb`, `myAdjective` ou `myAdverb`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -46,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should not directly use the values `dog`, `ran`, `big`, or `quickly` to create `wordBlanks`.
|
||||
Você não deve usar diretamente os valores `dog`, `ran`, `big` ou `quickly` para criar `wordBlanks`.
|
||||
|
||||
```js
|
||||
const newCode = removeAssignments(code);
|
||||
@ -58,7 +58,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`wordBlanks` should contain all of the words assigned to the variables `myNoun`, `myVerb`, `myAdjective` and `myAdverb` separated by non-word characters (and any additional words in your madlib).
|
||||
`wordBlanks` deve conter todas as palavras atribuídas às variáveis `myNoun`, `myVerb`, `myAdjective` e `myAdverb` separadas por caracteres que não sejam palavras (e qualquer palavra adicional na sua madlib).
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392cf
|
||||
title: Write Reusable JavaScript with Functions
|
||||
title: Escreva JavaScript Reutilizável com Funções
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cL6dqfy'
|
||||
forumTopicId: 18378
|
||||
@ -9,9 +9,9 @@ dashedName: write-reusable-javascript-with-functions
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, we can divide up our code into reusable parts called <dfn>functions</dfn>.
|
||||
Em JavaScript, nós podemos dividir nosso código em partes reutilizáveis chamadas de <dfn>functions</dfn>.
|
||||
|
||||
Here's an example of a function:
|
||||
Aqui está um exemplo de uma função:
|
||||
|
||||
```js
|
||||
function functionName() {
|
||||
@ -19,34 +19,34 @@ function functionName() {
|
||||
}
|
||||
```
|
||||
|
||||
You can call or <dfn>invoke</dfn> this function by using its name followed by parentheses, like this: `functionName();` Each time the function is called it will print out the message `Hello World` on the dev console. All of the code between the curly braces will be executed every time the function is called.
|
||||
Você pode chamar ou <dfn>invocar</dfn> essa função ao usar seu nome seguido de parênteses, da seguinte forma: `functionName();` Cada vez que a função é chamada irá imprimir no console a mensagem `Hello World`. Todo o código entre as chaves será executado toda vez que uma função for chamada.
|
||||
|
||||
# --instructions--
|
||||
|
||||
<ol>
|
||||
<li>
|
||||
Create a function called <code>reusableFunction</code> which prints the string <code>Hi World</code> to the dev console.
|
||||
Crie uma função chamada <code>reusableFunction</code> que imprime a string <code>Hi World</code> no console.
|
||||
</li>
|
||||
<li>
|
||||
Call the function.
|
||||
Chame a função.
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
# --hints--
|
||||
|
||||
`reusableFunction` should be a function.
|
||||
`reusableFunction` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof reusableFunction === 'function');
|
||||
```
|
||||
|
||||
If `reusableFunction` is called, it should output the string `Hi World` to the console.
|
||||
Se `reusableFunction` é chamada, deve exibir no console a string `Hi World`.
|
||||
|
||||
```js
|
||||
assert(testConsole());
|
||||
```
|
||||
|
||||
You should call `reusableFunction` once it is defined.
|
||||
Você deve chamar `reusableFunction` uma vez que for definida.
|
||||
|
||||
```js
|
||||
const functionStr = reusableFunction && __helpers.removeWhiteSpace(reusableFunction.toString());
|
||||
|
Reference in New Issue
Block a user