chore(i18n): download curriculum manually (#42835)
This commit is contained in:
committed by
GitHub
parent
2f8c5619ff
commit
fc0511bd91
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b85367417b2b2512b3a
|
||||
title: Catch Arguments Passed in the Wrong Order When Calling a Function
|
||||
title: Capture Argumentos Passados na Ordem Errada Quando Chamando uma Função
|
||||
challengeType: 1
|
||||
forumTopicId: 301184
|
||||
dashedName: catch-arguments-passed-in-the-wrong-order-when-calling-a-function
|
||||
@ -8,21 +8,21 @@ dashedName: catch-arguments-passed-in-the-wrong-order-when-calling-a-function
|
||||
|
||||
# --description--
|
||||
|
||||
Continuing the discussion on calling functions, the next bug to watch out for is when a function's arguments are supplied in the incorrect order. If the arguments are different types, such as a function expecting an array and an integer, this will likely throw a runtime error. If the arguments are the same type (all integers, for example), then the logic of the code won't make sense. Make sure to supply all required arguments, in the proper order to avoid these issues.
|
||||
Continuando a discussão sobre chamada de funções, o próximo bug para prestar atenção é quando os argumentos de uma função são fornecidos na ordem incorreta. Se os argumentos forem de diferentes tipos, tal como uma função esperando um array e um inteiro, isso irá provavelmente lançar um erro de tempo de execução. Se os argumentos são do mesmo tipo (todos os inteiros, por exemplo), então a lógica do código não fará sentido. Certifique-se de fornecer todos os argumentos exigidos, na ordem adequada para evitar esses problemas.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The function `raiseToPower` raises a base to an exponent. Unfortunately, it's not called properly - fix the code so the value of `power` is the expected 8.
|
||||
A função `raiseToPower` eleva uma base para um expoente. Infelizmente, não é chamada corretamente - corrija o código para que o valor de `power` seja o esperado 8.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should fix the variable `power` so it equals 2 raised to the 3rd power, not 3 raised to the 2nd power.
|
||||
Seu código deve corrigir a variável `power` para que seja igual a 2 elevado a 3ª potência, e não 3 elevado a 2ª potência.
|
||||
|
||||
```js
|
||||
assert(power == 8);
|
||||
```
|
||||
|
||||
Your code should use the correct order of the arguments for the `raiseToPower` function call.
|
||||
Seu código deve usar a ordem correta dos argumentos para a chamada da função `raiseToPower`.
|
||||
|
||||
```js
|
||||
assert(code.match(/raiseToPower\(\s*?base\s*?,\s*?exp\s*?\);/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b85367417b2b2512b39
|
||||
title: Catch Missing Open and Closing Parenthesis After a Function Call
|
||||
title: Capture Abertura e Fechamento de Parênteses Faltantes Após uma Chamada de Função
|
||||
challengeType: 1
|
||||
forumTopicId: 301185
|
||||
dashedName: catch-missing-open-and-closing-parenthesis-after-a-function-call
|
||||
@ -8,9 +8,9 @@ dashedName: catch-missing-open-and-closing-parenthesis-after-a-function-call
|
||||
|
||||
# --description--
|
||||
|
||||
When a function or method doesn't take any arguments, you may forget to include the (empty) opening and closing parentheses when calling it. Often times the result of a function call is saved in a variable for other use in your code. This error can be detected by logging variable values (or their types) to the console and seeing that one is set to a function reference, instead of the expected value the function returns.
|
||||
Quando uma função ou método não recebe nenhum parâmetro, você pode esquecer de incluir a abertura e fechamento de parênteses (vazio) ao chamá-la. Frequentemente, o resultado de uma chamada de função é salva em uma variável para outro uso em seu código. Esse erro pode ser detectado ao exibir no console os valores das variáveis (ou seus tipos) e verificar que uma variável está definida para uma referência de uma função, ao invés do valor esperado que a função retorna.
|
||||
|
||||
The variables in the following example are different:
|
||||
As variáveis no seguinte exemplo são diferentes:
|
||||
|
||||
```js
|
||||
function myFunction() {
|
||||
@ -20,21 +20,21 @@ let varOne = myFunction;
|
||||
let varTwo = myFunction();
|
||||
```
|
||||
|
||||
Here `varOne` is the function `myFunction`, and `varTwo` is the string `You rock!`.
|
||||
Aqui `varOne` é a função `myFunction` e `varTwo` é a string `You rock!`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the code so the variable `result` is set to the value returned from calling the function `getNine`.
|
||||
Corrija o código para que a variável `result` seja definida para o valor retornado da chamada da função `getNine`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should fix the variable `result` so it is set to the number that the function `getNine` returns.
|
||||
Seu código deve corrigir a variável `result` para que seja definida para o número que a função `getNine` retorna.
|
||||
|
||||
```js
|
||||
assert(result == 9);
|
||||
```
|
||||
|
||||
Your code should call the `getNine` function.
|
||||
Seu código deve chamar a função `getNine`.
|
||||
|
||||
```js
|
||||
assert(code.match(/getNine\(\)/g).length == 2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b84367417b2b2512b35
|
||||
title: Catch Misspelled Variable and Function Names
|
||||
title: Capture Nomes de Variáveis e Funções Com Erros Ortográficos
|
||||
challengeType: 1
|
||||
forumTopicId: 301186
|
||||
dashedName: catch-misspelled-variable-and-function-names
|
||||
@ -8,41 +8,41 @@ dashedName: catch-misspelled-variable-and-function-names
|
||||
|
||||
# --description--
|
||||
|
||||
The `console.log()` and `typeof` methods are the two primary ways to check intermediate values and types of program output. Now it's time to get into the common forms that bugs take. One syntax-level issue that fast typers can commiserate with is the humble spelling error.
|
||||
Os métodos `console.log()` e `typeof` são duas formas primárias para verificar valores intermediários e tipos de saída do programa. Agora é hora entrar nas formas comuns que um bug assume. Um problema de nível de sintaxe que digitadores rápidos podem ter passado é o humilde erro de digitação incorreta.
|
||||
|
||||
Transposed, missing, or mis-capitalized characters in a variable or function name will have the browser looking for an object that doesn't exist - and complain in the form of a reference error. JavaScript variable and function names are case-sensitive.
|
||||
Caracteres deslocados, faltando ou capitalizado erroneamente em um nome de variável ou função fará com que o navegador procure por um objeto que não existe - e reclamará na forma de um erro de referência. Variáveis e funções JavaScript são sensíveis a caracteres maiúsculos e minúsculos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the two spelling errors in the code so the `netWorkingCapital` calculation works.
|
||||
Corrija os dois erros de ortografia no código para que o cálculo `netWorkingCapital` funcione.
|
||||
|
||||
# --hints--
|
||||
|
||||
Check the spelling of the two variables used in the netWorkingCapital calculation, the console output should show that "Net working capital is: 2".
|
||||
Verifique a ortografia das duas variáveis usadas no cálculo de netWorkingCapital, a saída do console deve mostrar que "Net working capital is: 2".
|
||||
|
||||
```js
|
||||
assert(netWorkingCapital === 2);
|
||||
```
|
||||
|
||||
There should be no instances of mis-spelled variables in the code.
|
||||
Não deve haver instâncias de variáveis com ortografia incorretas no código.
|
||||
|
||||
```js
|
||||
assert(!code.match(/recievables/g));
|
||||
```
|
||||
|
||||
The `receivables` variable should be declared and used properly in the code.
|
||||
A variável `receivables` deve ser declarada e usada corretamente no código.
|
||||
|
||||
```js
|
||||
assert(code.match(/receivables/g).length == 2);
|
||||
```
|
||||
|
||||
There should be no instances of mis-spelled variables in the code.
|
||||
Não deve haver instâncias de variáveis com ortografia incorretas no código.
|
||||
|
||||
```js
|
||||
assert(!code.match(/payable;/g));
|
||||
```
|
||||
|
||||
The `payables` variable should be declared and used properly in the code.
|
||||
A variável `payables` deve ser declarada e usada corretamente no código.
|
||||
|
||||
```js
|
||||
assert(code.match(/payables/g).length == 2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b84367417b2b2512b37
|
||||
title: Catch Mixed Usage of Single and Double Quotes
|
||||
title: Identificar Uso Misto de Aspas Simples e Duplas
|
||||
challengeType: 1
|
||||
forumTopicId: 301188
|
||||
dashedName: catch-mixed-usage-of-single-and-double-quotes
|
||||
@ -8,21 +8,20 @@ dashedName: catch-mixed-usage-of-single-and-double-quotes
|
||||
|
||||
# --description--
|
||||
|
||||
JavaScript allows the use of both single (`'`) and double (`"`) quotes to declare a string. Deciding which one to use generally comes down to personal preference, with some exceptions.
|
||||
JavaScript nos permite o uso de ambas as aspas simples (`'<code>) e duplas (<code>"<code>) para declarar uma string. Decidir qual delas usar geralmente é uma questão de preferência pessoal, com algumas exceções.</p>
|
||||
|
||||
Having two choices is great when a string has contractions or another piece of text that's in quotes. Just be careful that you don't close the string too early, which causes a syntax error.
|
||||
<p spaces-before="0">Ter duas opções é ótimo quando uma string possui contrações ou outros pedaços de texto que estão entre aspas. Apenas tome cuidado para que você não feche uma string muito cedo, o que causa erro de sintaxe.</p>
|
||||
|
||||
Here are some examples of mixing quotes:
|
||||
<p spaces-before="0">Aqui estão alguns exemplos de mistura de aspas:</p>
|
||||
|
||||
```js
|
||||
const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it.";
|
||||
<pre><code class="js">const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it.";
|
||||
const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'";
|
||||
const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.';
|
||||
```
|
||||
`</pre>
|
||||
|
||||
The first two are correct, but the third is incorrect.
|
||||
As duas primeiras estão corretas, mas a terceira não.
|
||||
|
||||
Of course, it is okay to use only one style of quotes. You can escape the quotes inside the string by using the backslash (`\`) escape character:
|
||||
Claro, não há problema usar apenas um estilo de aspas. Você pode escapar as aspas dentro de uma string ao usar o caractere barra invertida (</code>\</code>):
|
||||
|
||||
```js
|
||||
const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.';
|
||||
@ -30,17 +29,17 @@ const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the string so it either uses different quotes for the `href` value, or escape the existing ones. Keep the double quote marks around the entire string.
|
||||
Corrija a string para que ou use aspas diferentes para o valor de `href` ou escape as aspas existentes. Mantenha as aspas duplas ao redor de toda a string.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should fix the quotes around the `href` value `#Home` by either changing or escaping them.
|
||||
Seu código deve corrigir as aspas em torno do valor de `href`: `#Home` ao mudar ou escapar elas.
|
||||
|
||||
```js
|
||||
assert(code.match(/<a href=\s*?('|\\")#Home\1\s*?>/g));
|
||||
```
|
||||
|
||||
Your code should keep the double quotes around the entire string.
|
||||
Seu código deve manter as aspas duplas ao redor de toda a string.
|
||||
|
||||
```js
|
||||
assert(code.match(/"<p>.*?<\/p>";/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b86367417b2b2512b3b
|
||||
title: Catch Off By One Errors When Using Indexing
|
||||
title: Capture Erros de Fora Por Um Quando Usando Indexação
|
||||
challengeType: 1
|
||||
forumTopicId: 301189
|
||||
dashedName: catch-off-by-one-errors-when-using-indexing
|
||||
@ -8,9 +8,9 @@ dashedName: catch-off-by-one-errors-when-using-indexing
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Off by one errors</dfn> (sometimes called OBOE) crop up when you're trying to target a specific index of a string or array (to slice or access a segment), or when looping over the indices of them. JavaScript indexing starts at zero, not one, which means the last index is always one less than the length of the item. If you try to access an index equal to the length, the program may throw an "index out of range" reference error or print `undefined`.
|
||||
<dfn>Off by one errors (erros de fora por um)</dfn> (as vezes chamado OBOE) surge quando você está tentando acessar um índice específico de uma string ou array (para fatiar ou acessar um segmento), ou quando você está iterando sobre seus índices. A indexação de JavaScript começa em zero e não um, o que significa que o último índice sempre será o tamanho do item menos 1 (array.length - 1). Se você estiver tentando acessar um índice igual ao tamanho, o programa pode lançar uma referência do erro "index out of range" ou imprimir `undefined`.
|
||||
|
||||
When you use string or array methods that take index ranges as arguments, it helps to read the documentation and understand if they are inclusive (the item at the given index is part of what's returned) or not. Here are some examples of off by one errors:
|
||||
Quando você usa métodos de string ou array que recebem intervalos de índices como argumentos, auxilia na leitura da documentação e compreender se eles são inclusivos (o item no índice especificado é parte do que é retornado) ou não. Aqui estão alguns exemplos de erros de fora por um:
|
||||
|
||||
```js
|
||||
let alphabet = "abcdefghijklmnopqrstuvwxyz";
|
||||
@ -26,33 +26,33 @@ for (let k = 0; k < len; k++) {
|
||||
}
|
||||
```
|
||||
|
||||
The first example here loops one too many times, and the second loops one too few times (missing the first index, 0). The third example is correct.
|
||||
O primeiro exemplo itera uma vez a mais (i <= len) e o segundo itera uma vez a menos por começar do índice 1 (let j = 1). O terceiro exemplo está certo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the two indexing errors in the following function so all the numbers 1 through 5 are printed to the console.
|
||||
Corrija os dois erros de índices nas funções seguintes para que todos os números de 1 até 5 sejam exibidos no console.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should set the initial condition of the loop so it starts at the first index.
|
||||
Seu código deve definir a condição inicial do laço para começar do primeiro índice.
|
||||
|
||||
```js
|
||||
assert(code.match(/i\s*?=\s*?0\s*?;/g).length == 1);
|
||||
```
|
||||
|
||||
Your code should fix the initial condition of the loop so that the index starts at 0.
|
||||
Seu código deve corrigir a condição inicial do laço para que o índice comece em 0.
|
||||
|
||||
```js
|
||||
assert(!code.match(/i\s?=\s*?1\s*?;/g));
|
||||
```
|
||||
|
||||
Your code should set the terminal condition of the loop so it stops at the last index.
|
||||
Seu código deve definir a condição de parada do laço, a fim de parar no último índice.
|
||||
|
||||
```js
|
||||
assert(code.match(/i\s*?<\s*?len\s*?;/g).length == 1);
|
||||
```
|
||||
|
||||
Your code should fix the terminal condition of the loop so that it stops at 1 before the length.
|
||||
Seu código deve corrigir a condição de parada do laço, a fim de parar no tamanho menos 1.
|
||||
|
||||
```js
|
||||
assert(!code.match(/i\s*?<=\s*?len;/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b84367417b2b2512b36
|
||||
title: 'Catch Unclosed Parentheses, Brackets, Braces and Quotes'
|
||||
title: 'Identifique Parênteses, Colchetes, Chaves e Aspas Sem Fechamento'
|
||||
challengeType: 1
|
||||
forumTopicId: 301190
|
||||
dashedName: catch-unclosed-parentheses-brackets-braces-and-quotes
|
||||
@ -8,23 +8,23 @@ dashedName: catch-unclosed-parentheses-brackets-braces-and-quotes
|
||||
|
||||
# --description--
|
||||
|
||||
Another syntax error to be aware of is that all opening parentheses, brackets, curly braces, and quotes have a closing pair. Forgetting a piece tends to happen when you're editing existing code and inserting items with one of the pair types. Also, take care when nesting code blocks into others, such as adding a callback function as an argument to a method.
|
||||
Outro erro de sintaxe para estar ciente é que todas as aberturas de parênteses, colchetes, chaves e aspas têm um par de fechamento. Esquecer um pedaço tende a acontecer quando você está editando um código existente e inserindo itens com um dos tipos de pares. Também, tenha cuidado ao aninhar blocos de código em outros, como adicionar uma função de callback como um argumento a um método.
|
||||
|
||||
One way to avoid this mistake is as soon as the opening character is typed, immediately include the closing match, then move the cursor back between them and continue coding. Fortunately, most modern code editors generate the second half of the pair automatically.
|
||||
Uma maneira de evitar esse erro é assim que o caractere de abertura é digitado, imediatamente inclua o caractere de fechamento, mova o cursor entre eles e continue programando. Felizmente, a maioria dos editores de código modernos geram a segunda parte do par automaticamente.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the two pair errors in the code.
|
||||
Corrija os dois erros de pares no código.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should fix the missing piece of the array.
|
||||
Seu código deve corrigir o pedaço que falta do array.
|
||||
|
||||
```js
|
||||
assert(code.match(/myArray\s*?=\s*?\[\s*?1\s*?,\s*?2\s*?,\s*?3\s*?\];/g));
|
||||
```
|
||||
|
||||
Your code should fix the missing piece of the `.reduce()` method. The console output should show that `Sum of array values is: 6`.
|
||||
Seu código deve corrigir o pedaço que falta do método `.reduce()`. A saída no console deve mostrar que `Sum of array value is: 6`.
|
||||
|
||||
```js
|
||||
assert(arraySum === 6);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b85367417b2b2512b38
|
||||
title: Catch Use of Assignment Operator Instead of Equality Operator
|
||||
title: Identifique Uso do Operador de Atribuição ao invés do Operador de Igualdade
|
||||
challengeType: 1
|
||||
forumTopicId: 301191
|
||||
dashedName: catch-use-of-assignment-operator-instead-of-equality-operator
|
||||
@ -8,13 +8,13 @@ dashedName: catch-use-of-assignment-operator-instead-of-equality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
Branching programs, i.e. ones that do different things if certain conditions are met, rely on `if`, `else if`, and `else` statements in JavaScript. The condition sometimes takes the form of testing whether a result is equal to a value.
|
||||
Programas de ramificação, ou seja, programas que fazem coisas diferentes se certas condições forem atendidas, dependem de instruções `i`, `else if` e `else` em JavaScript. Às vezes a condição verifica se um resultado é igual a um valor.
|
||||
|
||||
This logic is spoken (in English, at least) as "if x equals y, then ..." which can literally translate into code using the `=`, or assignment operator. This leads to unexpected control flow in your program.
|
||||
Essa lógica é fala da seguinte forma: "se x for igual a y, então ..." o que pode literalmente ser traduzido para código usando o `=`, ou operador de atribuição. Isso leva a um controle de fluxo inesperado no seu programa.
|
||||
|
||||
As covered in previous challenges, the assignment operator (`=`) in JavaScript assigns a value to a variable name. And the `==` and `===` operators check for equality (the triple `===` tests for strict equality, meaning both value and type are the same).
|
||||
Como abordado nos desafios anteriores, o operador de atribuição (`=`) em JavaScript, atribui um valor para o nome de uma variável. E os operadores `==` e `===` verificam pela igualdade (o triplo `===` testa por igualdade estrita, significando que ambos os valores e o tipo de dado são os mesmos).
|
||||
|
||||
The code below assigns `x` to be 2, which evaluates as `true`. Almost every value on its own in JavaScript evaluates to `true`, except what are known as the "falsy" values: `false`, `0`, `""` (an empty string), `NaN`, `undefined`, and `null`.
|
||||
O código abaixo atribui `x` para ser 2, o que tem como resultado `true`. Quase todo valor por si só em JavaScript são avaliados como `true`, exceto com o que são conhecidos como valores falsos: `false`, `0`, `""` (uma string vazia), `NaN`, `undefined` e `null`.
|
||||
|
||||
```js
|
||||
let x = 1;
|
||||
@ -26,21 +26,21 @@ if (x = y) {
|
||||
}
|
||||
```
|
||||
|
||||
In this example, the code block within the `if` statement will run for any value of `y`, unless `y` is falsy. The `else` block, which we expect to run here, will not actually run.
|
||||
Nesse exemplo, o bloco de código dentro da instrução `if` irá rodar para qualquer valor de `y`, a não ser que `y` seja falso. O bloco de `else`, que nós esperamos ser executado aqui, não irá realmente rodar.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the condition so the program runs the right branch, and the appropriate value is assigned to `result`.
|
||||
Corrija a condição para que o programa rode na ramificação correta e o valor apropriado seja atribuído a `result`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should fix the condition so it checks for equality, instead of using assignment.
|
||||
Seu código deve corrigir a condição para que verifique pela igualdade, ao invés de usar atribuição.
|
||||
|
||||
```js
|
||||
assert(result == 'Not equal!');
|
||||
```
|
||||
|
||||
The condition should use either `==` or `===` to test for equality.
|
||||
A condição deve usar `==` ou `===` para verificar a igualdade.
|
||||
|
||||
```js
|
||||
assert(code.match(/x\s*?===?\s*?y/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b86367417b2b2512b3d
|
||||
title: Prevent Infinite Loops with a Valid Terminal Condition
|
||||
title: Previna Laços Infinitos com uma Condição de Término Válida
|
||||
challengeType: 1
|
||||
forumTopicId: 301192
|
||||
dashedName: prevent-infinite-loops-with-a-valid-terminal-condition
|
||||
@ -8,9 +8,9 @@ dashedName: prevent-infinite-loops-with-a-valid-terminal-condition
|
||||
|
||||
# --description--
|
||||
|
||||
The final topic is the dreaded infinite loop. Loops are great tools when you need your program to run a code block a certain number of times or until a condition is met, but they need a terminal condition that ends the looping. Infinite loops are likely to freeze or crash the browser, and cause general program execution mayhem, which no one wants.
|
||||
O tópico final é o temido laço infinito. Laços são ótimas ferramentas quando você precisa que o seu programa rode um bloco de código uma quantidade exata de vezes ou até que uma condição seja atendida, mas eles precisam de uma condição de parada que finalize esse laço. Laços infinitos têm alta probabilidade de congelar ou travar o navegador, e causa um caos na execução geral do programa, o que ninguém deseja.
|
||||
|
||||
There was an example of an infinite loop in the introduction to this section - it had no terminal condition to break out of the `while` loop inside `loopy()`. Do NOT call this function!
|
||||
Havia um exemplo de laço infinito na introdução dessa seção - esse laço não tinha uma condição de parada para sair do laço `while` dentro de `loopy()`. NÃO chame essa função!
|
||||
|
||||
```js
|
||||
function loopy() {
|
||||
@ -20,21 +20,21 @@ function loopy() {
|
||||
}
|
||||
```
|
||||
|
||||
It's the programmer's job to ensure that the terminal condition, which tells the program when to break out of the loop code, is eventually reached. One error is incrementing or decrementing a counter variable in the wrong direction from the terminal condition. Another one is accidentally resetting a counter or index variable within the loop code, instead of incrementing or decrementing it.
|
||||
É trabalho do programador garantir que a condição de parada, a qual avisa ao programa quando sair de um laço, é eventualmente alcançada. Um erro é incrementar ou decrementar uma variável contadora na direção errada da condição de parada. Outro erro é acidentalmente reiniciar uma variável contadora ou de índice dentro do laço, ao invés de incrementar ou decrementar.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The `myFunc()` function contains an infinite loop because the terminal condition `i != 4` will never evaluate to `false` (and break the looping) - `i` will increment by 2 each pass, and jump right over 4 since `i` is odd to start. Fix the comparison operator in the terminal condition so the loop only runs for `i` less than or equal to 4.
|
||||
A função `myFunc()` contém um laço infinito porque a condição de parada `i != 4` nunca será `false` (e então quebrar o laço) - `i` irá incrementar em 2 a cada iteração, e passa direto por 4 já que `i` é ímpar no início. Corrija o operador de comparação para que o laço só rode enquanto `i` for menor ou igual a 4.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should change the comparison operator in the terminal condition (the middle part) of the `for` loop.
|
||||
Seu código deve alterar o operador de comparação na condição de parada (parte do meio) do laço `for`.
|
||||
|
||||
```js
|
||||
assert(code.match(/i\s*?<=\s*?4;/g).length == 1);
|
||||
```
|
||||
|
||||
Your code should fix the comparison operator in the terminal condition of the loop.
|
||||
Seu código deve corrigir o operador de comparação na condição de parada do laço.
|
||||
|
||||
```js
|
||||
assert(!code.match(/i\s*?!=\s*?4;/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b83367417b2b2512b37
|
||||
title: Understanding the Differences between the freeCodeCamp and Browser Console
|
||||
title: Entendendo a Diferença entre o console da freeCodeCamp e do Navegador
|
||||
challengeType: 1
|
||||
forumTopicId: 301193
|
||||
dashedName: understanding-the-differences-between-the-freecodecamp-and-browser-console
|
||||
@ -8,27 +8,27 @@ dashedName: understanding-the-differences-between-the-freecodecamp-and-browser-c
|
||||
|
||||
# --description--
|
||||
|
||||
You may have noticed that some freeCodeCamp JavaScript challenges include their own console. This console behaves a little differently than the browser console you used in the last challenge.
|
||||
Você pode ter percebido que alguns dos desafios de JavaScript da freeCodeCamp incluem seu próprio console. Esse console se comporta um pouco difrente do console do navegador que você utilizou no último desafio.
|
||||
|
||||
The following challenge is meant to highlight the main difference between the freeCodeCamp console and your browser console.
|
||||
O desafio a seguir tem a finalidade de destacar a principal diferença entre o console da freeCodeCamp e do navegador.
|
||||
|
||||
When you run ordinary JavaScript, the browser's console will display your `console.log()` statements the exact number of times it is called.
|
||||
Quando você executa JavaScript comum, o console do navegado exibirá suas instruções `console.log()` a exata quantidade de vezes que é chamada.
|
||||
|
||||
The freeCodeCamp console will print your `console.log()` statements a short time after the editor detects a change in the script, as well as during testing.
|
||||
O console da freeCodeCamp irá imprimir suas instruções `console.log()` um curto período depois do editor detectar mudança no script, e também durante o teste.
|
||||
|
||||
The freeCodeCamp console is cleared before the tests are run and, to avoid spam, only prints the logs during the first test (see the note below for exceptions).
|
||||
O console da freeCodeCamp é apagado antes de cada execução de testes e, para evitar spam, só imprime os logs durante o primeiro teste (veja a nota abaixo para exceções).
|
||||
|
||||
If you would like to see every log for every test, run the tests, and open the browser console. If you prefer to use the browser console, and want it to mimic the freeCodeCamp console, place `console.clear()` before any other `console` calls, to clear the browser console.
|
||||
Se você gostaria de ver todos os logs em todos os testes, execute os testes e abra o console do navegador. Se preferir usar o console do navegador e quiser que ele imite o console da freeCodeCamp, coloque `console.clear()` antes de qualquer outra chamada ao `console`, para apagar o console do navegador.
|
||||
|
||||
**Note:** `console.log`s inside functions are printed to the freeCodeCamp console whenever those functions are called. This can help debugging functions that are called during testing.
|
||||
**Nota:** `console.log` dentro de funções são impressas no console da freeCodeCamp toda vez que essas funções forem chamadas. Isso pode ajudar a depurar (ou debugar) funções que são chamadas durante os testes.
|
||||
|
||||
# --instructions--
|
||||
|
||||
First, use `console.log` to log the `output` variable. Then, use `console.clear` to clear the browser console.
|
||||
Primeiro, use `console.log` para exibir a variável `output`. Em seguida, use `console.clear` para apagar o console do navegador.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should use `console.clear()` to clear the browser console.
|
||||
Você deve usar `console.clear()` para apagar o console do navegador.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use `console.log()` to print the `output` variable.
|
||||
Você deve usar `console.log()` para imprimir a variável `output`.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/console\.log\(output\)/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b86367417b2b2512b3c
|
||||
title: Use Caution When Reinitializing Variables Inside a Loop
|
||||
title: Tenha Cuidado Quando Reinicializando Variáveis Dentro de Laços
|
||||
challengeType: 1
|
||||
forumTopicId: 301194
|
||||
dashedName: use-caution-when-reinitializing-variables-inside-a-loop
|
||||
@ -8,29 +8,29 @@ dashedName: use-caution-when-reinitializing-variables-inside-a-loop
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes it's necessary to save information, increment counters, or re-set variables within a loop. A potential issue is when variables either should be reinitialized, and aren't, or vice versa. This is particularly dangerous if you accidentally reset the variable being used for the terminal condition, causing an infinite loop.
|
||||
Às vezes é necessário salvar informações, incrementar contadores ou redefinir variáveis dentro de um laço. Um potencial problema é quando variáveis deveriam ser reinicializadas e, não são, ou vice versa. Isso é particularmente perigoso se você acidentalmente redefinir a variável sendo usada para a a condição de parada, causando um laço infinito.
|
||||
|
||||
Printing variable values with each cycle of your loop by using `console.log()` can uncover buggy behavior related to resetting, or failing to reset a variable.
|
||||
Imprimir os valores das variáveis em cada ciclo do seu laço usando `console.log()` pode descobrir comportamentos com bugs relacionados a reiniciar ou falhar ao reiniciar uma variável.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The following function is supposed to create a two-dimensional array with `m` rows and `n` columns of zeroes. Unfortunately, it's not producing the expected output because the `row` variable isn't being reinitialized (set back to an empty array) in the outer loop. Fix the code so it returns a correct 3x2 array of zeroes, which looks like `[[0, 0], [0, 0], [0, 0]]`.
|
||||
A seguinte função deveria criar um array de duas dimensões com `m` linhas e `n` colunas de zeros. Infelizmente, não está produzindo a saída esperada porque a variável `row` não está sendo reiniciada (definida de volta para um array vazio) no laço mais externo. Corrija o código para que retorne o array de zeros correto (dimensão: 3x2), que se parece com `[[0, 0], [0, 0], [0, 0]]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should set the `matrix` variable to an array holding 3 rows of 2 columns of zeroes each.
|
||||
Seu código deve definir a variável `matrix` para um array contendo 3 linhas de 2 colunas de zeros.
|
||||
|
||||
```js
|
||||
assert(JSON.stringify(matrix) == '[[0,0],[0,0],[0,0]]');
|
||||
```
|
||||
|
||||
The `matrix` variable should have 3 rows.
|
||||
A variável `matrix` deve ter 3 linhas.
|
||||
|
||||
```js
|
||||
assert(matrix.length == 3);
|
||||
```
|
||||
|
||||
The `matrix` variable should have 2 columns in each row.
|
||||
A variável `matrix` deve ter 2 colunas em cada linha.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b83367417b2b2512b33
|
||||
title: Use the JavaScript Console to Check the Value of a Variable
|
||||
title: Use o Console JavaScript para Verificar o Valor de uma Variável
|
||||
challengeType: 1
|
||||
forumTopicId: 18372
|
||||
dashedName: use-the-javascript-console-to-check-the-value-of-a-variable
|
||||
@ -8,13 +8,13 @@ dashedName: use-the-javascript-console-to-check-the-value-of-a-variable
|
||||
|
||||
# --description--
|
||||
|
||||
Both Chrome and Firefox have excellent JavaScript consoles, also known as DevTools, for debugging your JavaScript.
|
||||
Ambos o Chrome e o Firefox possui excelentes consoles JavaScript, também conhecidos como DevTools, para depurar seu JavaScript.
|
||||
|
||||
You can find Developer tools in your Chrome's menu or Web Console in Firefox's menu. If you're using a different browser, or a mobile phone, we strongly recommend switching to desktop Firefox or Chrome.
|
||||
Você pode encontrar Developer tools no menu do seu Chrome ou Web Console no menu do Firefox. Se você estiver usando um navegador diferente, ou um telefone móvel, recomendamos fortemente mudar para o Firefox ou Chrome Desktop.
|
||||
|
||||
The `console.log()` method, which "prints" the output of what's within its parentheses to the console, will likely be the most helpful debugging tool. Placing it at strategic points in your code can show you the intermediate values of variables. It's good practice to have an idea of what the output should be before looking at what it is. Having check points to see the status of your calculations throughout your code will help narrow down where the problem is.
|
||||
O método `console.log()`, o qual "imprime" a saída do que está nos seus parênteses no console, irá provavelmente ser a ferramenta de debug mais útil. Colocá-lo em pontos estratégicos no seu código pode te mostrar os valores intermediários de variáveis. É uma boa prática ter uma ideia do que deveria ser a saída antes de olhar o que é. Ter pontos de verificação para ver o status de seus cálculos ao longo do seu código ajudará a encontrar onde o problema está.
|
||||
|
||||
Here's an example to print the string `Hello world!` to the console:
|
||||
Aqui está um exemplo para imprimir a string `Hello world!` no console:
|
||||
|
||||
```js
|
||||
console.log('Hello world!');
|
||||
@ -22,11 +22,11 @@ console.log('Hello world!');
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `console.log()` method to print the value of the variable `a` where noted in the code.
|
||||
Use o método `console.log()` para imprimir o valor da variável `a` aonde anotou no código.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use `console.log()` to check the value of the variable `a`.
|
||||
Seu código deve usar `console.log()` para verificar o valor da variável `a`.
|
||||
|
||||
```js
|
||||
assert(code.match(/console\.log\(a\)/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b84367417b2b2512b34
|
||||
title: Use typeof to Check the Type of a Variable
|
||||
title: Use typeof para Verificar o Tipo da Variável
|
||||
challengeType: 1
|
||||
forumTopicId: 18374
|
||||
dashedName: use-typeof-to-check-the-type-of-a-variable
|
||||
@ -8,9 +8,9 @@ dashedName: use-typeof-to-check-the-type-of-a-variable
|
||||
|
||||
# --description--
|
||||
|
||||
You can use `typeof` to check the data structure, or type, of a variable. This is useful in debugging when working with multiple data types. If you think you're adding two numbers, but one is actually a string, the results can be unexpected. Type errors can lurk in calculations or function calls. Be careful especially when you're accessing and working with external data in the form of a JavaScript Object Notation (JSON) object.
|
||||
Você pode usar `typeof` para verificar a estrutura de dado, ou tipo, de uma variável. Isso é útil na depuração quando trabalhando com diversos tipos de dados. Se você pensar que está adicionando dois números, mas na verdade um é na verdade uma string, o resultado pode ser inesperado. Erros de tipo podem se esconder em cálculos ou chamada de funções. Seja cuidadoso especialmente quando você estiver acessando e trabalhando com dados externos na forma de um objeto JavaScript Object Notation (JSON).
|
||||
|
||||
Here are some examples using `typeof`:
|
||||
Aqui está alguns exemplos usando `typeof`:
|
||||
|
||||
```js
|
||||
console.log(typeof "");
|
||||
@ -19,29 +19,29 @@ console.log(typeof []);
|
||||
console.log(typeof {});
|
||||
```
|
||||
|
||||
In order, the console will display the strings `string`, `number`, `object`, and `object`.
|
||||
Em ordem, o console exibirá as strings `string`, `number`, `object` e `object`.
|
||||
|
||||
JavaScript recognizes six primitive (immutable) data types: `Boolean`, `Null`, `Undefined`, `Number`, `String`, and `Symbol` (new with ES6) and one type for mutable items: `Object`. Note that in JavaScript, arrays are technically a type of object.
|
||||
JavaScript reconhece seis tipos de dados primitivos (imutável): `Boolean`, `Null`, `Undefined`, `Number`, `String` e `Symbol` (novo em ES6) e um tipo para itens mutáveis: `Object`. Note que em JavaScript, arrays são tecnicamente um tipo de objeto.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add two `console.log()` statements to check the `typeof` each of the two variables `seven` and `three` in the code.
|
||||
Adicione duas instruções `console.log()` para verificar o `typeof` de cada uma das duas variáveis `seven` e `three` no código.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use `typeof` in two `console.log()` statements to check the type of the variables.
|
||||
Seu código deve usar `typeof` em duas instruções `console.log()` para verificar o tipo das variáveis.
|
||||
|
||||
```js
|
||||
assert(code.match(/console\.log\(typeof[\( ].*\)?\)/g).length == 2);
|
||||
```
|
||||
|
||||
Your code should use `typeof` to check the type of the variable `seven`.
|
||||
Seu código deve usar `typeof` para verificar o tipo da variável `seven`.
|
||||
|
||||
```js
|
||||
assert(code.match(/typeof[\( ]seven\)?/g));
|
||||
```
|
||||
|
||||
Your code should use `typeof` to check the type of the variable `three`.
|
||||
Seu código deve usar `typeof` para verificar o tipo da variável `three`.
|
||||
|
||||
```js
|
||||
assert(code.match(/typeof[\( ]three\)?/g));
|
||||
|
Reference in New Issue
Block a user