chore(i18n): download curriculum manually (#42835)
This commit is contained in:
committed by
GitHub
parent
2f8c5619ff
commit
fc0511bd91
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b87367417b2b2512b40
|
||||
title: Compare Scopes of the var and let Keywords
|
||||
title: Compare Escopos das Palavras-Chaves var e let
|
||||
challengeType: 1
|
||||
forumTopicId: 301195
|
||||
dashedName: compare-scopes-of-the-var-and-let-keywords
|
||||
@ -8,11 +8,11 @@ dashedName: compare-scopes-of-the-var-and-let-keywords
|
||||
|
||||
# --description--
|
||||
|
||||
When you declare a variable with the `var` keyword, it is declared globally, or locally if declared inside a function.
|
||||
Quando você declara uma variável com a palavra-chave `var`, ela é declarada globalmente, ou localmente se declarada dentro de uma função.
|
||||
|
||||
The `let` keyword behaves similarly, but with some extra features. When you declare a variable with the `let` keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.
|
||||
A palvara-chave `let` se comporta de forma similar, mas com alguns recursos extras. Quando você declara a variável com a palavra-chave `let` dentro de um bloco, declaração, ou expressão, seu escopo é limitado ao bloco, declaração, ou expressão.
|
||||
|
||||
For example:
|
||||
Por exemplo:
|
||||
|
||||
```js
|
||||
var numArray = [];
|
||||
@ -23,9 +23,9 @@ console.log(numArray);
|
||||
console.log(i);
|
||||
```
|
||||
|
||||
Here the console will display the values `[0, 1, 2]` and `3`.
|
||||
Aqui o console irá exibir os valores `[0, 1, 2]` e `3`.
|
||||
|
||||
With the `var` keyword, `i` is declared globally. So when `i++` is executed, it updates the global variable. This code is similar to the following:
|
||||
Com a palavra-chave `var`, `i` é declarado globalmente. Então quando `i++` é executado, ele atualiza a variável global. Esse código é semelhante ao seguinte:
|
||||
|
||||
```js
|
||||
var numArray = [];
|
||||
@ -37,9 +37,9 @@ console.log(numArray);
|
||||
console.log(i);
|
||||
```
|
||||
|
||||
Here the console will display the values `[0, 1, 2]` and `3`.
|
||||
Aqui o console irá exibir os valores `[0, 1, 2]` e `3`.
|
||||
|
||||
This behavior will cause problems if you were to create a function and store it for later use inside a `for` loop that uses the `i` variable. This is because the stored function will always refer to the value of the updated global `i` variable.
|
||||
Este comportamento causará problemas se você criasse uma função e armazená-la para depois utilizar dentro de um laço `for` que utiliza a variável `i`. Isso se deve ao fato da função armazenada sempre irá se referir ao valor da variável global `i` atualizada.
|
||||
|
||||
```js
|
||||
var printNumTwo;
|
||||
@ -53,9 +53,9 @@ for (var i = 0; i < 3; i++) {
|
||||
console.log(printNumTwo());
|
||||
```
|
||||
|
||||
Here the console will display the value `3`.
|
||||
Aqui o console irá exibir o valor `3`.
|
||||
|
||||
As you can see, `printNumTwo()` prints 3 and not 2. This is because the value assigned to `i` was updated and the `printNumTwo()` returns the global `i` and not the value `i` had when the function was created in the for loop. The `let` keyword does not follow this behavior:
|
||||
Como você pode ver, `printNumTwo()` exibe 3 e não 2. Isso se deve ao fato do valor atribuído a `i` foi atualizado e `printNumTwo()` retorna a variável global `i` e não o valor que `i` tinha quando a função foi criada dentro do laço for. A palavra-chave `let` não segue este comportamento:
|
||||
|
||||
```js
|
||||
let printNumTwo;
|
||||
@ -70,25 +70,25 @@ console.log(printNumTwo());
|
||||
console.log(i);
|
||||
```
|
||||
|
||||
Here the console will display the value `2`, and an error that `i is not defined`.
|
||||
Aqui o console irá exibir o valor `2`, e um erro que `i is not defined (i não foi definido)`.
|
||||
|
||||
`i` is not defined because it was not declared in the global scope. It is only declared within the `for` loop statement. `printNumTwo()` returned the correct value because three different `i` variables with unique values (0, 1, and 2) were created by the `let` keyword within the loop statement.
|
||||
`i` não foi definido porque não foi declarado no escopo global. É declarado apenas dentro da declaração do laço `for`. `printNumTwo()` retornou o valor correto porque três variáveis `i` distintas com valores únicos (0, 1 e 2) foram criados com a palavra-chave `let` dentro da declaração do laço.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Fix the code so that `i` declared in the `if` statement is a separate variable than `i` declared in the first line of the function. Be certain not to use the `var` keyword anywhere in your code.
|
||||
Corrija o código para que `i` declarado dentro do comando `if` seja uma variável diferente de `i` declarada na primeira linha da função. Tenha certeza de não usar a palavra-chave `var` em nenhum lugar do seu código.
|
||||
|
||||
This exercise is designed to illustrate the difference between how `var` and `let` keywords assign scope to the declared variable. When programming a function similar to the one used in this exercise, it is often better to use different variable names to avoid confusion.
|
||||
Este exercício foi projetado para ilustrar a diferença ente como as palavras-chaves `var` e `let` definem o escopo para a variável declarada. Quando programamos uma função semelhar a aquelas utilizadas no exercício, geralmente é melhor utilizar variáveis distintas para evitar confusão.
|
||||
|
||||
# --hints--
|
||||
|
||||
`var` should not exist in code.
|
||||
`var` não deve existir no código.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
The variable `i` declared in the `if` statement should equal the string `block scope`.
|
||||
A variável `i` declarada dentro do corpo do comando `if` deve ser igual a string `block scope`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -97,7 +97,7 @@ The variable `i` declared in the `if` statement should equal the string `block s
|
||||
);
|
||||
```
|
||||
|
||||
`checkScope()` should return the string `function scope`
|
||||
`checkScope()` deve retornar a string `function scope`
|
||||
|
||||
```js
|
||||
assert(checkScope() === 'function scope');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cdafbc32913098997531680
|
||||
title: Complete a Promise with resolve and reject
|
||||
title: Concluir uma Promessa com resolve e reject
|
||||
challengeType: 1
|
||||
forumTopicId: 301196
|
||||
dashedName: complete-a-promise-with-resolve-and-reject
|
||||
@ -8,7 +8,7 @@ dashedName: complete-a-promise-with-resolve-and-reject
|
||||
|
||||
# --description--
|
||||
|
||||
A promise has three states: `pending`, `fulfilled`, and `rejected`. The promise you created in the last challenge is forever stuck in the `pending` state because you did not add a way to complete the promise. The `resolve` and `reject` parameters given to the promise argument are used to do this. `resolve` is used when you want your promise to succeed, and `reject` is used when you want it to fail. These are methods that take an argument, as seen below.
|
||||
Uma promessa possui três estados: pendente (`pending`), cumprida (`fulfilled`) e rejeitada (`rejected`). A promessa que você criou no desafio anterior está presa no estado `pending` para sempre porque você não adicionou uma forma de concluir a promessa. Os parâmetros `resolve` e `reject` passados para o argumento da promessa servem para este propósito. `resolve` é utilizado quando a promessa for bem sucedida, enquanto que `reject` é utilizado quando ela falhar. Ambos são métodos que recebem apenas um argumento, como no exemplo abaixo.
|
||||
|
||||
```js
|
||||
const myPromise = new Promise((resolve, reject) => {
|
||||
@ -20,15 +20,15 @@ const myPromise = new Promise((resolve, reject) => {
|
||||
});
|
||||
```
|
||||
|
||||
The example above uses strings for the argument of these functions, but it can really be anything. Often, it might be an object, that you would use data from, to put on your website or elsewhere.
|
||||
O exemplo acima usa strings como argumento desses métodos, mas você pode passar qualquer outro tipo de dado. Geralmente, é passado um objeto para esses métodos. Assim você pode acessar as propriedades deste objeto e usá-los em seu site ou em qualquer outro lugar.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Make the promise handle success and failure. If `responseFromServer` is `true`, call the `resolve` method to successfully complete the promise. Pass `resolve` a string with the value `We got the data`. If `responseFromServer` is `false`, use the `reject` method instead and pass it the string: `Data not received`.
|
||||
Adapte a promessa para ambas as situações de sucesso e fracasso. Se `responseFromServer` for `true`, chame o método `resolve` para completar a promessa com sucesso. Passe a string `We got the data` como argumento para o método `resolve`. Se `responseFromServer` for `false`, passe a string `Data not received` como argumento para o método `reject`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`resolve` should be called with the expected string when the `if` condition is `true`.
|
||||
O método `resolve` deve ser chamado com a string informada anteriormente quando a condição do `if` for `true`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -36,7 +36,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`reject` should be called with the expected string when the `if` condition is `false`.
|
||||
O método `reject` deve ser chamado com a string informada anteriormente quando a condição do `if` for `false`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cdafbb0291309899753167f
|
||||
title: Create a JavaScript Promise
|
||||
title: Criar uma Promessa em JavaScript
|
||||
challengeType: 1
|
||||
forumTopicId: 301197
|
||||
dashedName: create-a-javascript-promise
|
||||
@ -8,7 +8,7 @@ dashedName: create-a-javascript-promise
|
||||
|
||||
# --description--
|
||||
|
||||
A promise in JavaScript is exactly what it sounds like - you use it to make a promise to do something, usually asynchronously. When the task completes, you either fulfill your promise or fail to do so. `Promise` is a constructor function, so you need to use the `new` keyword to create one. It takes a function, as its argument, with two parameters - `resolve` and `reject`. These are methods used to determine the outcome of the promise. The syntax looks like this:
|
||||
Uma promessa em JavaScript é exatamente o que parece - você faz a promessa de que irá fazer uma tarefa, geralmente de forma assíncrona. Quando a tarefa é finalizada, ou você cumpriu a promessa ou falhou ao tentar. Por ser uma função construtora, você precisa utilizar a palavra-chave `new` para criar uma `Promise`. Ele recebe uma função, como seu arguemento, com dois parâmetros - `resolve` e `reject`. Esses métodos são usados para determinar o resultado da promessa. A sintaxe se parecesse com isso:
|
||||
|
||||
```js
|
||||
const myPromise = new Promise((resolve, reject) => {
|
||||
@ -18,17 +18,17 @@ const myPromise = new Promise((resolve, reject) => {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a new promise called `makeServerRequest`. Pass in a function with `resolve` and `reject` parameters to the constructor.
|
||||
Crie uma nova promessa chamada `makeServerRequest`. No construtor da promessa, passe uma função com os parâmetros `resolve` e `reject`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should assign a promise to a declared variable named `makeServerRequest`.
|
||||
Você deve atribuir a promessa a uma variável chamada `makeServerRequest`.
|
||||
|
||||
```js
|
||||
assert(makeServerRequest instanceof Promise);
|
||||
```
|
||||
|
||||
Your promise should receive a function with `resolve` and `reject` as parameters.
|
||||
A promessa deve receber uma função com os parâmetros `resolve` e `reject`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cddbfd622f1a59093ec611d
|
||||
title: Create a Module Script
|
||||
title: Separar seus scripts em módulos
|
||||
challengeType: 6
|
||||
forumTopicId: 301198
|
||||
dashedName: create-a-module-script
|
||||
@ -8,27 +8,27 @@ dashedName: create-a-module-script
|
||||
|
||||
# --description--
|
||||
|
||||
JavaScript started with a small role to play on an otherwise mostly HTML web. Today, it’s huge, and some websites are built almost entirely with JavaScript. In order to make JavaScript more modular, clean, and maintainable; ES6 introduced a way to easily share code among JavaScript files. This involves exporting parts of a file for use in one or more other files, and importing the parts you need, where you need them. In order to take advantage of this functionality, you need to create a script in your HTML document with a `type` of `module`. Here’s an example:
|
||||
O JavaScript nasceu com com o objetivo de cumprir um pequeno papel em uma web onde tudo era, na maior parte, HTML. Hoje, o JavaScript é gigante. Para se ter noção, alguns websites são construídos quase que inteiramente em JavaScript. A fim de tornar o JavaScript mais modular, limpo e passível de manutenção, a versão ES6 introduziu uma forma mais simples de compartilhar códigos entre arquivos JavaScript. Dessa forma, você consegue exportar partes de um arquivo e usá-los em arquivos externos bem como importar as partes que você precisa. Para tirar proveito dessa funcionalidade, você precisa crair uma tag script com o atributo `type` de valor `module` no seu documento HTML. Aqui está um exemplo:
|
||||
|
||||
```html
|
||||
<script type="module" src="filename.js"></script>
|
||||
```
|
||||
|
||||
A script that uses this `module` type can now use the `import` and `export` features you will learn about in the upcoming challenges.
|
||||
O script do exemplo acima agora é um módulo (`module`) e pode usar os recursos `import` e `export` (você aprenderá sobre eles nos próximos desafios).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a script to the HTML document of type `module` and give it the source file of `index.js`
|
||||
Adicione uma tag script ao documento HTML do tipo `module` e dê a ela o caminho do arquivo `index.js`
|
||||
|
||||
# --hints--
|
||||
|
||||
You should create a `script` tag.
|
||||
Você deve criar uma tag `script`.
|
||||
|
||||
```js
|
||||
assert(code.match(/<\s*script[^>]*>\s*<\/\s*script\s*>/g));
|
||||
```
|
||||
|
||||
Your `script` tag should have the `type` attribute with a value of `module`.
|
||||
A tag `script` deve ter o atributo `type` com o valor `module`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `script` tag should have a `src` of `index.js`.
|
||||
A tag `script` deve ter o atributo `src` com o valor `index.js`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8c367417b2b2512b58
|
||||
title: Create an Export Fallback with export default
|
||||
title: Exportar apenas um valor com export default
|
||||
challengeType: 1
|
||||
forumTopicId: 301199
|
||||
dashedName: create-an-export-fallback-with-export-default
|
||||
@ -8,11 +8,11 @@ dashedName: create-an-export-fallback-with-export-default
|
||||
|
||||
# --description--
|
||||
|
||||
In the `export` lesson, you learned about the syntax referred to as a <dfn>named export</dfn>. This allowed you to make multiple functions and variables available for use in other files.
|
||||
Na lição de `export` você aprendeu sobre a sintaxe que chamamos de <dfn>exportação nomeada</dfn>. Naquela lição você exportou múltiplas funções e variáveis que ficaram disponíveis para utilização em outros arquivos.
|
||||
|
||||
There is another `export` syntax you need to know, known as <dfn>export default</dfn>. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.
|
||||
Há outra sintaxe para `export` que você precisa saber, conhecida como <dfn>exportação padrão</dfn>. Você usará essa sintaxe quando apenas um valor estiver sendo exportado de um arquivo ou módulo. Essa sintaxe também é usada para exportar um valor substituto caso o valor original não possa ser exportado.
|
||||
|
||||
Below are examples using `export default`:
|
||||
Abaixo estão exemplos utilizando a sintaxe `export default`:
|
||||
|
||||
```js
|
||||
export default function add(x, y) {
|
||||
@ -24,17 +24,17 @@ export default function(x, y) {
|
||||
}
|
||||
```
|
||||
|
||||
The first is a named function, and the second is an anonymous function.
|
||||
O primeiro exemplo é uma função nomeada e o segundo é uma função anônima.
|
||||
|
||||
Since `export default` is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use `export default` with `var`, `let`, or `const`
|
||||
A sintaxe `export default` é usada para exportar um único valor de um arquivo ou módulo. Tenha em mente que você não pode usar o `export default` com `var`, `let` ou `const`
|
||||
|
||||
# --instructions--
|
||||
|
||||
The following function should be the fallback value for the module. Please add the necessary code to do so.
|
||||
A função a seguir deve ser o único valor a ser exportado. Adicione o código necessário para que apenas um valor seja exportado.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should use an `export` fallback.
|
||||
Você deve usar a sintaxe alternativa ao `export`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8a367417b2b2512b4e
|
||||
title: Create Strings using Template Literals
|
||||
title: Criar Strings usando Template Literals
|
||||
challengeType: 1
|
||||
forumTopicId: 301200
|
||||
dashedName: create-strings-using-template-literals
|
||||
@ -8,11 +8,11 @@ dashedName: create-strings-using-template-literals
|
||||
|
||||
# --description--
|
||||
|
||||
A new feature of ES6 is the <dfn>template literal</dfn>. This is a special type of string that makes creating complex strings easier.
|
||||
Um novo recurso introduzido na versão ES6 é o <dfn>template literal</dfn>. Esse é um tipo especial de string que torna mais fácil a criação de strings complexas.
|
||||
|
||||
Template literals allow you to create multi-line strings and to use string interpolation features to create strings.
|
||||
Template literals nos permite criar strings de mais de uma linha e usar os recursos de interpolação de strings.
|
||||
|
||||
Consider the code below:
|
||||
Considere o código abaixo:
|
||||
|
||||
```js
|
||||
const person = {
|
||||
@ -26,15 +26,15 @@ I am ${person.age} years old.`;
|
||||
console.log(greeting);
|
||||
```
|
||||
|
||||
The console will display the strings `Hello, my name is Zodiac Hasbro!` and `I am 56 years old.`.
|
||||
O console irá exibir as strings `Hello, my name is Zodiac Hasbro!` e `I am 56 years old.`.
|
||||
|
||||
A lot of things happened there. Firstly, the example uses backticks (`` ` ``), not quotes (`'` or `"`), to wrap the string. Secondly, notice that the string is multi-line, both in the code and the output. This saves inserting `\n` within strings. The `${variable}` syntax used above is a placeholder. Basically, you won't have to use concatenation with the `+` operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with `${` and `}`. Similarly, you can include other expressions in your string literal, for example `${a + b}`. This new way of creating strings gives you more flexibility to create robust strings.
|
||||
Muitas coisas aconteceram aqui. Primeiro, o exemplo utiliza crases, ou backticks em Inglês, (`` ` ``), ao invés de aspas (`'` ou `"`), ao redor da string. Segundo, note que a string tem mais de uma linha, tanto no código quanto na saída. Isso torna desnecessário inserir `\n` dentro das strings. A sintaxe `${variable}` usada acima é um espaço reservado (placeholder). Basicamente, você não terá mais que usar concatenação com o operador `+`. Para adicionar o valor de uma variável à string, você a envolve com `${` e `}`. Além de poder usar variáveis, você pode incluir outras expressões. Como por exemplo `${a + b}`. Essa nova maneira de criar strings te dá mais flexibilidade na hora de criar string complexas.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use template literal syntax with backticks to create an array of list element (`li`) strings. Each list element's text should be one of the array elements from the `failure` property on the `result` object and have a `class` attribute with the value `text-warning`. The `makeList` function should return the array of list item strings.
|
||||
Use a sintaxe de template literal com crases para criar um array de strings de elementos de lista (`li`). Analise a propriedade `failure` do objeto `result`. O texto de cada elemento li deve ser um dos elementos contidos no array dentro da propriedade failure e cada li deve ter o atributo `class` com o valor `text-warning`. A função `makeList` deve retornar um array de strings de elementos li.
|
||||
|
||||
Use an iterator method (any kind of loop) to get the desired output (shown below).
|
||||
Abaixo está um exemplo do array que você deve criar. Use um loop para criar o mesmo resultado.
|
||||
|
||||
```js
|
||||
[
|
||||
@ -46,7 +46,7 @@ Use an iterator method (any kind of loop) to get the desired output (shown below
|
||||
|
||||
# --hints--
|
||||
|
||||
`failuresList` should be an array containing `result failure` messages.
|
||||
A variável `failuresList` deve ser um array contendo as mensagens de `result failure`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,7 +54,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`failuresList` should be equal to the specified output.
|
||||
A variável `failuresList` deve ser igual ao array mostrado anteriormente.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -66,13 +66,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Template strings and expression interpolation should be used.
|
||||
Template strings e interpolação de expressões - ${} - devem ser usados.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(`.*\${.*}.*`)/));
|
||||
```
|
||||
|
||||
An iterator should be used.
|
||||
Você deve usar um loop.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b87367417b2b2512b41
|
||||
title: Declare a Read-Only Variable with the const Keyword
|
||||
title: Declare variáveis somente de leitura com a palavra-chave const
|
||||
challengeType: 1
|
||||
forumTopicId: 301201
|
||||
dashedName: declare-a-read-only-variable-with-the-const-keyword
|
||||
@ -8,46 +8,46 @@ dashedName: declare-a-read-only-variable-with-the-const-keyword
|
||||
|
||||
# --description--
|
||||
|
||||
The keyword `let` is not the only new way to declare variables. In ES6, you can also declare variables using the `const` keyword.
|
||||
A palavra-chave `let` não é a única nova forma de declarar variáveis. Na versão ES6, você também pode declarar variáveis usando a palavra-chave `const`.
|
||||
|
||||
`const` has all the awesome features that `let` has, with the added bonus that variables declared using `const` are read-only. They are a constant value, which means that once a variable is assigned with `const`, it cannot be reassigned.
|
||||
`const` possui todos os recursos maravilhosos que `let` tem, com o bônus adicional que variáveis declaradas usando `const` são somente de leitura. Eles são um valor constante, o que significa que uma vez que a variável é atribuída com `const`, não pode ser atribuída novamente.
|
||||
|
||||
```js
|
||||
const FAV_PET = "Cats";
|
||||
FAV_PET = "Dogs";
|
||||
```
|
||||
|
||||
The console will display an error due to reassigning the value of `FAV_PET`.
|
||||
O console irá exibir um erro devido à reatribuição do valor de `FAV_PET`.
|
||||
|
||||
As you can see, trying to reassign a variable declared with `const` will throw an error. You should always name variables you don't want to reassign using the `const` keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice when naming constants is to use all uppercase letters, with words separated by an underscore.
|
||||
Como você pode ver, tentar reatribuir uma variável declarada com `const` lançará um erro. Você sempre deve nomear variáveis que você não quer reatribuir, usando a palavra-chave `const`. Isso ajuda quando você acidentalmente tenta reatribuir uma variável que deveria ser constante. Uma prática comum ao nomear constantes é colocar todas as letras em maiúsculas, com palavras separadas por sublinhado (underscore ou underline).
|
||||
|
||||
**Note:** It is common for developers to use uppercase variable identifiers for immutable values and lowercase or camelCase for mutable values (objects and arrays). In a later challenge you will see an example of a lowercase variable identifier being used for an array.
|
||||
**Observação:** É comum que os desenvolvedores usem nomes de variáveis maiúsculas para valores imutáveis e minúsculas ou camelCase para valores mutáveis (objetos e arrays). Em um desafio posterior, você verá um exemplo de um nome de variável em minúsculo usado para um array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the code so that all variables are declared using `let` or `const`. Use `let` when you want the variable to change, and `const` when you want the variable to remain constant. Also, rename variables declared with `const` to conform to common practices, meaning constants should be in all caps.
|
||||
Altere o código para que todas as variáveis sejam declaradas usando `let` ou `const`. Use `let` quando você quiser que a variável mude e `const` quando você quiser que a variável permaneça constante. Além disso, renomeie as variáveis declaradas com `const` para estar em conformidade com as práticas comuns, o que significa que constantes devem ter todas as letras em maiúsculo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`var` should not exist in your code.
|
||||
`var` não deve existir no seu código.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
`SENTENCE` should be a constant variable declared with `const`.
|
||||
`SENTENCE` deve ser uma variável constante declarada com `const`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(const SENTENCE)/g));
|
||||
```
|
||||
|
||||
`i` should be declared with `let`.
|
||||
A variável `i` deve ser declarada com `let`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/(let i)/g));
|
||||
```
|
||||
|
||||
`console.log` should be changed to print the `SENTENCE` variable.
|
||||
`console.log` deve ser alterado para imprimir a variável `SENTENCE`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b87367417b2b2512b3f
|
||||
title: Explore Differences Between the var and let Keywords
|
||||
title: Diferenças entre as palavras-chave var e let
|
||||
challengeType: 1
|
||||
forumTopicId: 301202
|
||||
dashedName: explore-differences-between-the-var-and-let-keywords
|
||||
@ -8,7 +8,7 @@ dashedName: explore-differences-between-the-var-and-let-keywords
|
||||
|
||||
# --description--
|
||||
|
||||
One of the biggest problems with declaring variables with the `var` keyword is that you can overwrite variable declarations without an error.
|
||||
Um dos maiores problemas ao declarar variáveis com a palavra-chave `var` é que você pode sobrescrever a declaração da variável sem perceber.
|
||||
|
||||
```js
|
||||
var camper = 'James';
|
||||
@ -16,44 +16,44 @@ var camper = 'David';
|
||||
console.log(camper);
|
||||
```
|
||||
|
||||
Here the console will display the string `David`.
|
||||
Aqui o console irá exibir a string `David`.
|
||||
|
||||
As you can see in the code above, the `camper` variable is originally declared as `James` and then overridden to be `David`. In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite. Because this behavior does not throw an error, searching and fixing bugs becomes more difficult.
|
||||
A new keyword called `let` was introduced in ES6 to solve this potential issue with the `var` keyword. If you were to replace `var` with `let` in the variable declarations of the code above, the result would be an error.
|
||||
Como você pode ver no código acima, a variável `camper` é originalmente declarada com o valor `James` e então substituída pelo valor `David`. Em uma aplicação pequena, você pode não encontrar esse tipo de problema, mas quando seu código se tornar maior, você pode acidentalmente sobrescrever uma variável que você não tinha a intenção. Como esse comportamente não lança nenhum erro, procurar e corrigir bugs se torna mais difícil.
|
||||
Para resolver esse potencial problema com a palavra-chave `var`, uma nova palavra-chave chamada `let` foi introduzida no ES6. Se você tentar substituir `var` por `let` nas declarações de variável do código acima, o resultado será um erro.
|
||||
|
||||
```js
|
||||
let camper = 'James';
|
||||
let camper = 'David';
|
||||
```
|
||||
|
||||
This error can be seen in the console of your browser. So unlike `var`, when using `let`, a variable with the same name can only be declared once. Note the `"use strict"`. This enables Strict Mode, which catches common coding mistakes and "unsafe" actions. For instance:
|
||||
Esse erro pode ser visto no console do seu navegador. Então, diferente de `var`, ao usar `let`, uma variável com o mesmo nome só pode ser declarada uma única vez. Note o `"use strict"`. Isso habilita o Modo Estrito, o qual captura erros de codificação comum e ações "não seguras". Por exemplo:
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
x = 3.14;
|
||||
```
|
||||
|
||||
This will display an error that `x is not defined`.
|
||||
O ´codigo acima irá exibir o erro: `x is not defined`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Update the code so it only uses the `let` keyword.
|
||||
Atualize o código para que apenas a palavra-chave `let` seja usada.
|
||||
|
||||
# --hints--
|
||||
|
||||
`var` should not exist in the code.
|
||||
A palavra-chave `var` não deve existir no código.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
`catName` should be the string `Oliver`.
|
||||
A variável `catName` deve ser uma string de valor `Oliver`.
|
||||
|
||||
```js
|
||||
assert(catName === 'Oliver');
|
||||
```
|
||||
|
||||
`quote` should be the string `Oliver says Meow!`
|
||||
A variável `quote` deve ser uma string de valor `Oliver says Meow!`
|
||||
|
||||
```js
|
||||
assert(quote === 'Oliver says Meow!');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cdafbd72913098997531681
|
||||
title: Handle a Fulfilled Promise with then
|
||||
title: Manipular uma promessa cumprida usando o then
|
||||
challengeType: 1
|
||||
forumTopicId: 301203
|
||||
dashedName: handle-a-fulfilled-promise-with-then
|
||||
@ -8,7 +8,7 @@ dashedName: handle-a-fulfilled-promise-with-then
|
||||
|
||||
# --description--
|
||||
|
||||
Promises are most useful when you have a process that takes an unknown amount of time in your code (i.e. something asynchronous), often a server request. When you make a server request it takes some amount of time, and after it completes you usually want to do something with the response from the server. This can be achieved by using the `then` method. The `then` method is executed immediately after your promise is fulfilled with `resolve`. Here’s an example:
|
||||
Promessas são úteis quando você tem um processo que leva uma quantidade de tempo desconhecido para ser finalizado (ou seja, algo assíncrono). Muitas vezes, uma requisição a um servidor. Fazer uma requisição a um servidor leva tempo, e após a requisição ser finalizada, você geralmente quer fazer algo com a resposta retornada. Isso pode ser feito usando o método `then`. O método `then` é executado imediatamente após a promessa ser cumprida com `resolve`. Aqui está um exemplo:
|
||||
|
||||
```js
|
||||
myPromise.then(result => {
|
||||
@ -16,15 +16,15 @@ myPromise.then(result => {
|
||||
});
|
||||
```
|
||||
|
||||
`result` comes from the argument given to the `resolve` method.
|
||||
O parâmetro `result` vem do argumento dado ao método `resolve`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the `then` method to your promise. Use `result` as the parameter of its callback function and log `result` to the console.
|
||||
Adicione o método `then` à sua promessa. Use `result` como parâmetro de sua função de callback e exiba `result` no console.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should call the `then` method on the promise.
|
||||
Você deve chamar o método `then` na promessa.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -32,13 +32,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `then` method should have a callback function with `result` as its parameter.
|
||||
O método `then` deve ter uma função de callback com `result` como seu parâmetro.
|
||||
|
||||
```js
|
||||
assert(resultIsParameter);
|
||||
```
|
||||
|
||||
You should log `result` to the console.
|
||||
Você deve exibir o valor do parâmetro `result` no console.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cdafbe72913098997531682
|
||||
title: Handle a Rejected Promise with catch
|
||||
title: Manipular uma promessa rejeitada usando o catch
|
||||
challengeType: 1
|
||||
forumTopicId: 301204
|
||||
dashedName: handle-a-rejected-promise-with-catch
|
||||
@ -8,7 +8,7 @@ dashedName: handle-a-rejected-promise-with-catch
|
||||
|
||||
# --description--
|
||||
|
||||
`catch` is the method used when your promise has been rejected. It is executed immediately after a promise's `reject` method is called. Here’s the syntax:
|
||||
`catch` é o método usado quando a promessa é rejeitada. Ele é executada imediatamente após o método `reject` da promessa ser chamado. Aqui está a sintaxe:
|
||||
|
||||
```js
|
||||
myPromise.catch(error => {
|
||||
@ -16,15 +16,15 @@ myPromise.catch(error => {
|
||||
});
|
||||
```
|
||||
|
||||
`error` is the argument passed in to the `reject` method.
|
||||
O parâmetro `error` é o argumento passado para o método `reject`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the `catch` method to your promise. Use `error` as the parameter of its callback function and log `error` to the console.
|
||||
Adicione o método `catch` à sua promessa. Use `error` como parâmetro de sua função de callback e exiba o valor de `error` no console.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should call the `catch` method on the promise.
|
||||
Você deve chamar o método `catch` na promessa.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -32,13 +32,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `catch` method should have a callback function with `error` as its parameter.
|
||||
O método `catch` deve ter uma função de callback com `error` como seu parâmetro.
|
||||
|
||||
```js
|
||||
assert(errorIsParameter);
|
||||
```
|
||||
|
||||
You should log `error` to the console.
|
||||
Você deve exibir o valor de `error` no console.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8d367417b2b2512b59
|
||||
title: Import a Default Export
|
||||
title: Importar uma exportação padrão
|
||||
challengeType: 1
|
||||
forumTopicId: 301205
|
||||
dashedName: import-a-default-export
|
||||
@ -8,21 +8,21 @@ dashedName: import-a-default-export
|
||||
|
||||
# --description--
|
||||
|
||||
In the last challenge, you learned about `export default` and its uses. To import a default export, you need to use a different `import` syntax. In the following example, `add` is the default export of the `math_functions.js` file. Here is how to import it:
|
||||
No último desafio, você aprendeu sobre `export default` e seus usos. Para importar uma exportação padrão, você precisa usar uma sintaxe diferente de `import`. No exemplo a seguir, `add` é a exportação padrão do arquivo `math_functions.js`. Veja como importá-lo:
|
||||
|
||||
```js
|
||||
import add from "./math_functions.js";
|
||||
```
|
||||
|
||||
The syntax differs in one key place. The imported value, `add`, is not surrounded by curly braces (`{}`). `add` here is simply a variable name for whatever the default export of the `math_functions.js` file is. You can use any name here when importing a default.
|
||||
A sintaxe é diferente em apenas um ponto. O valor importado, `add`, não está rodeado por chaves (`{}`). Aqui, `add` é simplesmente uma palavra qualquer que irá ser usada para identificar a variável sendo exportada do arquivo `math_functions.js`. Você pode usar qualquer nome ao importar algo que foi exportado como padrão.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In the following code, import the default export from the `math_functions.js` file, found in the same directory as this file. Give the import the name `subtract`.
|
||||
No código a seguir, importe a exportação padrão do arquivo `math_functions.js` encontrado no mesmo diretório do arquivo que foi usado como exemplo. Dê a importação o nome `subtract`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should properly import `subtract` from `math_functions.js`.
|
||||
A única coisa que você precisa fazer é importar `subtract` do arquivo `math_functions.js`.
|
||||
|
||||
```js
|
||||
assert(code.match(/import\s+subtract\s+from\s+('|")\.\/math_functions\.js\1/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b87367417b2b2512b42
|
||||
title: Mutate an Array Declared with const
|
||||
title: Modificar um array declarado com const
|
||||
challengeType: 1
|
||||
forumTopicId: 301206
|
||||
dashedName: mutate-an-array-declared-with-const
|
||||
@ -8,11 +8,11 @@ dashedName: mutate-an-array-declared-with-const
|
||||
|
||||
# --description--
|
||||
|
||||
The `const` declaration has many use cases in modern JavaScript.
|
||||
Variáveis declaradas com `const` têm muitos casos de uso no JavaScript moderno.
|
||||
|
||||
Some developers prefer to assign all their variables using `const` by default, unless they know they will need to reassign the value. Only in that case, they use `let`.
|
||||
Alguns desenvolvedores preferem criar todas suas variáveis usando `const`, a menos que eles saibam que irão precisar reatribuir o valor. Apenas nesse caso, eles usam `let`.
|
||||
|
||||
However, it is important to understand that objects (including arrays and functions) assigned to a variable using `const` are still mutable. Using the `const` declaration only prevents reassignment of the variable identifier.
|
||||
No entanto, é importante entender que objetos (incluindo arrays e funções) atribuídos a uma variável usando `const` ainda são mutáveis. Usar a declaração `const` só impede a reatribuição do identificador (nome) da variável.
|
||||
|
||||
```js
|
||||
const s = [5, 6, 7];
|
||||
@ -21,29 +21,29 @@ s[2] = 45;
|
||||
console.log(s);
|
||||
```
|
||||
|
||||
`s = [1, 2, 3]` will result in an error. The `console.log` will display the value `[5, 6, 45]`.
|
||||
`s = [1, 2, 3]` resultará em um erro. `console.log` exibirá o valor `[5, 6, 45]`.
|
||||
|
||||
As you can see, you can mutate the object `[5, 6, 7]` itself and the variable `s` will still point to the altered array `[5, 6, 45]`. Like all arrays, the array elements in `s` are mutable, but because `const` was used, you cannot use the variable identifier `s` to point to a different array using the assignment operator.
|
||||
Como você pode ver, você pode alterar o objeto `[5, 6, 7]` e a variável `s` ainda apontará para o array alterado `[5, 6, 45]`. Assim como em qualquer outro array, os elementos dentro de `s` também são mutáveis. Mas como `const` foi usado, você não pode usar o identificador da variável `s` para apontar para uma matriz diferente (ou qualquer outro valor) usando o operador de atribuição.
|
||||
|
||||
# --instructions--
|
||||
|
||||
An array is declared as `const s = [5, 7, 2]`. Change the array to `[2, 5, 7]` using various element assignments.
|
||||
Um array é declarado: `const s = [5, 7, 2]`. Modifique o array para `[2, 5, 7]` usando várias atribuições de elementos.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not replace `const` keyword.
|
||||
Você não deve substituir a palavra-chave `const`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/const/g));
|
||||
```
|
||||
|
||||
`s` should be a constant variable (by using `const`).
|
||||
`s` deve ser uma variável constante (use `const`).
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/const\s+s/g));
|
||||
```
|
||||
|
||||
You should not change the original array declaration.
|
||||
Você não deve alterar modificar o array original manualmente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -54,7 +54,7 @@ You should not change the original array declaration.
|
||||
);
|
||||
```
|
||||
|
||||
`s` should be equal to `[2, 5, 7]`.
|
||||
A variável `s` deve ser igual a `[2, 5, 7]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(s, [2, 5, 7]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 598f48a36c8c40764b4e52b3
|
||||
title: Prevent Object Mutation
|
||||
title: Impedir a modificação de um objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301207
|
||||
dashedName: prevent-object-mutation
|
||||
@ -8,9 +8,9 @@ dashedName: prevent-object-mutation
|
||||
|
||||
# --description--
|
||||
|
||||
As seen in the previous challenge, `const` declaration alone doesn't really protect your data from mutation. To ensure your data doesn't change, JavaScript provides a function `Object.freeze` to prevent data mutation.
|
||||
Como visto no desafio anterior, a declaração `const` sozinha, na verdade, não protege a mutação de seus dados. Para garantir que seus dados não mudem, o JavaScript fornece a função `Object.freeze` que previne os dados de serem modificados.
|
||||
|
||||
Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error.
|
||||
Uma vez congelado, você não pode mais adicionar, atualizar ou deletar as propriedades deste objeto. Qualquer tentativa de mudar o objeto será rejeitada. Observe que nenhum erro é lançado.
|
||||
|
||||
```js
|
||||
let obj = {
|
||||
@ -23,28 +23,28 @@ obj.newProp = "Test";
|
||||
console.log(obj);
|
||||
```
|
||||
|
||||
The `obj.review` and `obj.newProp` assignments will result in errors, and the console will display the value `{ name: "FreeCodeCamp", review: "Awesome" }`.
|
||||
As atribuições `obj.review` e `obj.newProp` não irão funcionar e o console irá exibir o valor `{ name: "FreeCodeCamp", review: "Awesome" }`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In this challenge you are going to use `Object.freeze` to prevent mathematical constants from changing. You need to freeze the `MATH_CONSTANTS` object so that no one is able to alter the value of `PI`, add, or delete properties.
|
||||
Nesse desafio, você usará o método `Object.freeze` para prevenir a mudança de constantes matemáticas. Você precisa congelar o objeto `MATH_CONSTANTS` para que ninguém possa alterar o valor de `PI`, adicionar ou deletar propriedades.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not replace the `const` keyword.
|
||||
Você não deve substituir a palavra-chave `const`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/const/g));
|
||||
```
|
||||
|
||||
`MATH_CONSTANTS` should be a constant variable (by using `const`).
|
||||
`MATH_CONSTANTS` deve ser uma variável constante (use `const`).
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
assert(getUserInput('index').match(/const\s+MATH_CONSTANTS/g));
|
||||
```
|
||||
|
||||
You should not change the original declaration of `MATH_CONSTANTS`.
|
||||
Você não deve alterar a declaração original de `MATH_CONSTANTS`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -55,7 +55,7 @@ You should not change the original declaration of `MATH_CONSTANTS`.
|
||||
);
|
||||
```
|
||||
|
||||
`PI` should equal `3.14`.
|
||||
A variável `PI` deve ser igual a `3.14`.
|
||||
|
||||
```js
|
||||
assert(PI === 3.14);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8c367417b2b2512b55
|
||||
title: Reuse JavaScript Code Using import
|
||||
title: Reutilizar código JavaScript usando import
|
||||
challengeType: 1
|
||||
forumTopicId: 301208
|
||||
dashedName: reuse-javascript-code-using-import
|
||||
@ -8,15 +8,15 @@ dashedName: reuse-javascript-code-using-import
|
||||
|
||||
# --description--
|
||||
|
||||
`import` allows you to choose which parts of a file or module to load. In the previous lesson, the examples exported `add` from the `math_functions.js` file. Here's how you can import it to use in another file:
|
||||
`import` te permite escolher quais partes carregar de um arquivo ou módulo. Na lição anterior, os exemplos exportaram a função `add` do arquivo `math_functions.js`. Você pode importá-la e usá-la em outro arquivo assim:
|
||||
|
||||
```js
|
||||
import { add } from './math_functions.js';
|
||||
```
|
||||
|
||||
Here, `import` will find `add` in `math_functions.js`, import just that function for you to use, and ignore the rest. The `./` tells the import to look for the `math_functions.js` file in the same folder as the current file. The relative file path (`./`) and file extension (`.js`) are required when using import in this way.
|
||||
Aqui, `import` irá encontrar a função `add` no arquivo `math_functions.js`, importar apenas essa função e ignorar o resto. O `./` diz ao import para procurar pelo arquivo `math_functions.js` no mesmo diretório que o arquivo atual. O caminho relativo do arquivo (`./`) e a extensão do arquivo (`.js`) são necessários ao usar import dessa forma.
|
||||
|
||||
You can import more than one item from the file by adding them in the `import` statement like this:
|
||||
Você pode importar mais de um item do arquivo ao adicioná-los na instrução `import` dessa forma:
|
||||
|
||||
```js
|
||||
import { add, subtract } from './math_functions.js';
|
||||
@ -24,11 +24,11 @@ import { add, subtract } from './math_functions.js';
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the appropriate `import` statement that will allow the current file to use the `uppercaseString` and `lowercaseString` functions you exported in the previous lesson. These functions are in a file called `string_functions.js`, which is in the same directory as the current file.
|
||||
Adicione a instrução `import` apropriada que permitirá o arquivo atual usar as funções `uppercaseString` e `lowercaseString` que você exportou na lição anterior. As funções estão em um arquivo chamado `string_functions.js`, o qual está no mesmo diretório que o arquivo atual.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should properly import `uppercaseString`.
|
||||
Você deve importar a função `uppercaseString`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should properly import `lowercaseString`.
|
||||
Você deve importar a função `lowercaseString`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b88367417b2b2512b46
|
||||
title: Set Default Parameters for Your Functions
|
||||
title: Definir um valor padrão para o parâmetro de uma função
|
||||
challengeType: 1
|
||||
forumTopicId: 301209
|
||||
dashedName: set-default-parameters-for-your-functions
|
||||
@ -8,9 +8,9 @@ dashedName: set-default-parameters-for-your-functions
|
||||
|
||||
# --description--
|
||||
|
||||
In order to help us create more flexible functions, ES6 introduces <dfn>default parameters</dfn> for functions.
|
||||
Para nos ajudar a criar funções mais flexíveis, a versão ES6 introduziu os <dfn>parâmetros padrão</dfn> para funções.
|
||||
|
||||
Check out this code:
|
||||
Confira este código:
|
||||
|
||||
```js
|
||||
const greeting = (name = "Anonymous") => "Hello " + name;
|
||||
@ -19,29 +19,29 @@ console.log(greeting("John"));
|
||||
console.log(greeting());
|
||||
```
|
||||
|
||||
The console will display the strings `Hello John` and `Hello Anonymous`.
|
||||
O console exibirá as strings `Hello John` e `Hello Anonymous`.
|
||||
|
||||
The default parameter kicks in when the argument is not specified (it is undefined). As you can see in the example above, the parameter `name` will receive its default value `Anonymous` when you do not provide a value for the parameter. You can add default values for as many parameters as you want.
|
||||
O parâmetro padrão é usado quando o argumento não é especificado (ele não é definido). Como você pode ver no exemplo acima, o parâmetro `name` receberá o valor padrão `Anonymous` quando você não fornecer um valor para o parâmetro. Você pode adicionar valores padrão para quantos parâmetros quiser.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the function `increment` by adding default parameters so that it will add 1 to `number` if `value` is not specified.
|
||||
Modifique a função `increment` adicionando parâmetros padrão para que ela adicione 1 à variável `number` se o parâmetro `value` não for especificado.
|
||||
|
||||
# --hints--
|
||||
|
||||
The result of `increment(5, 2)` should be `7`.
|
||||
O resultado de `increment(5, 2)` deve ser `7`.
|
||||
|
||||
```js
|
||||
assert(increment(5, 2) === 7);
|
||||
```
|
||||
|
||||
The result of `increment(5)` should be `6`.
|
||||
O resultado de `increment(5)` deve ser `6`.
|
||||
|
||||
```js
|
||||
assert(increment(5) === 6);
|
||||
```
|
||||
|
||||
A default parameter value of `1` should be used for `value`.
|
||||
O parâmetro padrão (`value`) deve receber o valor `1`.
|
||||
|
||||
```js
|
||||
assert(code.match(/value\s*=\s*1/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8c367417b2b2512b57
|
||||
title: Use * to Import Everything from a File
|
||||
title: Use * para importar tudo de um arquivo
|
||||
challengeType: 1
|
||||
forumTopicId: 301210
|
||||
dashedName: use--to-import-everything-from-a-file
|
||||
@ -8,13 +8,13 @@ dashedName: use--to-import-everything-from-a-file
|
||||
|
||||
# --description--
|
||||
|
||||
Suppose you have a file and you wish to import all of its contents into the current file. This can be done with the `import * as` syntax. Here's an example where the contents of a file named `math_functions.js` are imported into a file in the same directory:
|
||||
Suponha que você tem um arquivo e deseja importar todo o conteúdo dele no arquivo atual. Isso pode ser feito com a sintaxe `import * as`. Aqui está um exemplo onde todo o conteúdo de um arquivo chamado `math_function.js` é importado em um arquivo no mesmo diretório:
|
||||
|
||||
```js
|
||||
import * as myMathModule from "./math_functions.js";
|
||||
```
|
||||
|
||||
The above `import` statement will create an object called `myMathModule`. This is just a variable name, you can name it anything. The object will contain all of the exports from `math_functions.js` in it, so you can access the functions like you would any other object property. Here's how you can use the `add` and `subtract` functions that were imported:
|
||||
A instrução `import` acima criará um objeto chamado `myMathModule`. Esse nome é totalmente arbitrário. Você pode escolher qualquer outro nome que seja apropriado para sua aplicação. O objeto conterá todas as exportações do arquivo `math_functions.js`. Dessa forma, você pode acessar as funções exportadas da mesma forma que você acessa as propriedades de um objeto. Aqui está um exemplo de como você pode usar as funções `add` e `subtract` que foram importadas:
|
||||
|
||||
```js
|
||||
myMathModule.add(2,3);
|
||||
@ -23,11 +23,11 @@ myMathModule.subtract(5,3);
|
||||
|
||||
# --instructions--
|
||||
|
||||
The code in this file requires the contents of the file: `string_functions.js`, that is in the same directory as the current file. Use the `import * as` syntax to import everything from the file into an object called `stringFunctions`.
|
||||
O código nesse desafio requer o conteúdo do arquivo: `string_functions.js`, o qual está no mesmo diretório que o arquivo atual. Use a sintaxe `import * as` para importar tudo do arquivo em um objeto chamado `stringFunctions`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your code should properly use `import * as` syntax.
|
||||
Você deve usar a sintaxe `import * as`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b87367417b2b2512b43
|
||||
title: Use Arrow Functions to Write Concise Anonymous Functions
|
||||
title: Criar funções anônimas com arrow functions
|
||||
challengeType: 1
|
||||
forumTopicId: 301211
|
||||
dashedName: use-arrow-functions-to-write-concise-anonymous-functions
|
||||
@ -8,9 +8,9 @@ dashedName: use-arrow-functions-to-write-concise-anonymous-functions
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we create inline functions. We don't need to name these functions because we do not reuse them anywhere else.
|
||||
No JavaScript, muitas vezes não precisamos nomear nossas funções, especialmente quando passamos uma função como argumento para outra função. Em vez disso, criamos funções anônimas. Como não iremos reutilizar essas funções posteriormente, não precisamos nomeá-las.
|
||||
|
||||
To achieve this, we often use the following syntax:
|
||||
Para fazer isso, geralmente usamos a seguinte sintaxe:
|
||||
|
||||
```js
|
||||
const myFunc = function() {
|
||||
@ -19,7 +19,7 @@ const myFunc = function() {
|
||||
}
|
||||
```
|
||||
|
||||
ES6 provides us with the syntactic sugar to not have to write anonymous functions this way. Instead, you can use **arrow function syntax**:
|
||||
ES6 nos fornece um <dfn>syntatical sugar</dfn> onde não precisamos escrever funções anônimas como no exemplo acima. Ao invés disso, você pode usar a sintaxe **arrow function**:
|
||||
|
||||
```js
|
||||
const myFunc = () => {
|
||||
@ -28,45 +28,45 @@ const myFunc = () => {
|
||||
}
|
||||
```
|
||||
|
||||
When there is no function body, and only a return value, arrow function syntax allows you to omit the keyword `return` as well as the brackets surrounding the code. This helps simplify smaller functions into one-line statements:
|
||||
Quando a função executa apenas uma linha de código ou retorna apenas um valor, a sintaxe de arrow function nos permite omitir a palavra-chave `return` assim como as chaves ao redor do código. Essa abordagem ajuda a criar funções menores em instruções de uma linha:
|
||||
|
||||
```js
|
||||
const myFunc = () => "value";
|
||||
```
|
||||
|
||||
This code will still return the string `value` by default.
|
||||
Esse código ainda retornará a string `value` por padrão.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Rewrite the function assigned to the variable `magic` which returns a `new Date()` to use arrow function syntax. Also, make sure nothing is defined using the keyword `var`.
|
||||
Rescreva a função atribuída à variável `magic` usando a sintaxe de arrow function. A função deve retornar `new Date()`. Além disso, garanta que nada seja definido usando a palavra-chave `var`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should replace the `var` keyword.
|
||||
Você deve substituir a palavra-chave `var`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
`magic` should be a constant variable (by using `const`).
|
||||
A variável `magic` deve ser uma variável constante (use `const`).
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/const\s+magic/g));
|
||||
```
|
||||
|
||||
`magic` should be a `function`.
|
||||
A variável `magic` deve ser uma `function`.
|
||||
|
||||
```js
|
||||
assert(typeof magic === 'function');
|
||||
```
|
||||
|
||||
`magic()` should return the correct date.
|
||||
Ao invocar `magic()`, uma data deve ser retornada.
|
||||
|
||||
```js
|
||||
assert(magic().setHours(0, 0, 0, 0) === new Date().setHours(0, 0, 0, 0));
|
||||
```
|
||||
|
||||
The `function` keyword should not be used.
|
||||
A palavra-chave `function` não deve ser usada.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/function/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8b367417b2b2512b53
|
||||
title: Use class Syntax to Define a Constructor Function
|
||||
title: Use a sintaxe de classe para criar uma função construtora
|
||||
challengeType: 1
|
||||
forumTopicId: 301212
|
||||
dashedName: use-class-syntax-to-define-a-constructor-function
|
||||
@ -8,11 +8,11 @@ dashedName: use-class-syntax-to-define-a-constructor-function
|
||||
|
||||
# --description--
|
||||
|
||||
ES6 provides a new syntax to create objects, using the <dfn>class</dfn> keyword.
|
||||
ES6 fornece uma nova sintaxe para criar objetos, usando a palavra-chave <dfn>class</dfn>.
|
||||
|
||||
It should be noted that the `class` syntax is just syntax, and not a full-fledged class-based implementation of an object-oriented paradigm, unlike in languages such as Java, Python, Ruby, etc.
|
||||
Deve ser notado que a sintaxe `class` é apenas sintaxe, um <dfn>syntatical sugar</dfn>. JavaScript ainda não oferece suporte completo ao paradigma orientado a objetos, ao contrário do que acontece em linguagens como Java, Python, Ruby, etc.
|
||||
|
||||
In ES5, we usually define a `constructor` function and use the `new` keyword to instantiate an object.
|
||||
No ES5, geralmente definimos uma função construtora (`constructor` function) e usamos a palavra-chave `new` para instanciar um objeto.
|
||||
|
||||
```js
|
||||
var SpaceShuttle = function(targetPlanet){
|
||||
@ -21,7 +21,7 @@ var SpaceShuttle = function(targetPlanet){
|
||||
var zeus = new SpaceShuttle('Jupiter');
|
||||
```
|
||||
|
||||
The `class` syntax simply replaces the `constructor` function creation:
|
||||
A sintaxe `class` simplesmente substitui a criação da função construtora (`constructor`):
|
||||
|
||||
```js
|
||||
class SpaceShuttle {
|
||||
@ -32,21 +32,21 @@ class SpaceShuttle {
|
||||
const zeus = new SpaceShuttle('Jupiter');
|
||||
```
|
||||
|
||||
It should be noted that the `class` keyword declares a new function, to which a constructor is added. This constructor is invoked when `new` is called to create a new object.
|
||||
Deve ser notado que a palavra-chave `class` declara uma nova função, para qual um construtor é adicionado. Esse construtor é invocado quando `new` é chamado na criação de um novo objeto.
|
||||
|
||||
**Note:** UpperCamelCase should be used by convention for ES6 class names, as in `SpaceShuttle` used above.
|
||||
**Observação:** UpperCamelCase (observe a primeira letra de cada palavra em maiúsculo) deve ser usado por convenção para nomes de classe no ES6, como em `SpaceShuttle` usado acima.
|
||||
|
||||
The `constructor` method is a special method for creating and initializing an object created with a class. You will learn more about it in the Object Oriented Programming section of the JavaScript Algorithms And Data Structures Certification.
|
||||
O método `constructor` é um método especial usado para inicializar um objeto criado com uma classe. Você aprenderá mais sobre isso na seção Programação Orientada a Objetos da Certificação de Algoritmos e Estruturas de Dados JavaScript.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `class` keyword and write a `constructor` to create the `Vegetable` class.
|
||||
Use a palavra-chave `class` e declare o método `constructor` para criar a classe `Vegetable`.
|
||||
|
||||
The `Vegetable` class allows you to create a vegetable object with a property `name` that gets passed to the `constructor`.
|
||||
A classe `Vegetable` permite criar um objeto vegetal com a propriedade `name` que é passada ao `constructor`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Vegetable` should be a `class` with a defined `constructor` method.
|
||||
`Vegetable` deve ser uma `class` com um método `constructor` definido.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,13 +54,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `class` keyword should be used.
|
||||
A palavra-chave `class` deve ser usada.
|
||||
|
||||
```js
|
||||
assert(code.match(/class/g));
|
||||
```
|
||||
|
||||
`Vegetable` should be able to be instantiated.
|
||||
A classe `Vegetable` deve poder ser instanciada.
|
||||
|
||||
```js
|
||||
assert(() => {
|
||||
@ -69,7 +69,7 @@ assert(() => {
|
||||
});
|
||||
```
|
||||
|
||||
`carrot.name` should return `carrot`.
|
||||
`carrot.name` deve retornar a string `carrot`.
|
||||
|
||||
```js
|
||||
assert(carrot.name == 'carrot');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b89367417b2b2512b4b
|
||||
title: Use Destructuring Assignment to Assign Variables from Arrays
|
||||
title: Use Atribuição de Desestruturação para Atribuir Variáveis de Arrays
|
||||
challengeType: 1
|
||||
forumTopicId: 301213
|
||||
dashedName: use-destructuring-assignment-to-assign-variables-from-arrays
|
||||
@ -8,47 +8,47 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
ES6 makes destructuring arrays as easy as destructuring objects.
|
||||
ES6 torna desestruturar arrays tão fácil quanto desestruturar objetos.
|
||||
|
||||
One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables.
|
||||
Uma diferença chave entre o operador spread (...) e a desestruturação de array é que o operador spread retira todos os conteúdos de um array e coloca em uma lista com elementos separados por vírgula. Consequentemente, você não pode pegar ou escolher quais elementos você quer atribuir a variáveis.
|
||||
|
||||
Destructuring an array lets us do exactly that:
|
||||
Desestruturar um array nos permite fazer exatamente isso:
|
||||
|
||||
```js
|
||||
const [a, b] = [1, 2, 3, 4, 5, 6];
|
||||
console.log(a, b);
|
||||
```
|
||||
|
||||
The console will display the values of `a` and `b` as `1, 2`.
|
||||
O console exibirá os valores de `a` e `b` como `1, 2`.
|
||||
|
||||
The variable `a` is assigned the first value of the array, and `b` is assigned the second value of the array. We can also access the value at any index in an array with destructuring by using commas to reach the desired index:
|
||||
É atribuída à variável `a` o primeiro valor do array, e à variável `b` é atribuído o segundo valor do array. Nós também podemos acessar o valor em qualquer índice de um array com desestruturação ao usar vírgulas para alcançar o índice desejado:
|
||||
|
||||
```js
|
||||
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
|
||||
console.log(a, b, c);
|
||||
```
|
||||
|
||||
The console will display the values of `a`, `b`, and `c` as `1, 2, 5`.
|
||||
O console exibirá os valores de `a`, `b` e `c` como `1, 2, 5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use destructuring assignment to swap the values of `a` and `b` so that `a` receives the value stored in `b`, and `b` receives the value stored in `a`.
|
||||
Use atribuição de desestruturação para trocar os valores de `a` e `b` para que `a` receba os valores armazenados em `b` e `b` recebe os valores armazenados em `a`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The value of `a` should be `6`, after swapping.
|
||||
O valor de `a` deve ser `6`, após a troca.
|
||||
|
||||
```js
|
||||
assert(a === 6);
|
||||
```
|
||||
|
||||
The value of `b` should be `8`, after swapping.
|
||||
O valor de `b` deve ser `8`, após a troca.
|
||||
|
||||
```js
|
||||
assert(b === 8);
|
||||
```
|
||||
|
||||
You should use array destructuring to swap `a` and `b`.
|
||||
Você deve usar desestruturação de array para trocar `a` e `b`.
|
||||
|
||||
```js
|
||||
assert(/\[\s*(\w)\s*,\s*(\w)\s*\]\s*=\s*\[\s*\2\s*,\s*\1\s*\]/g.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b89367417b2b2512b4a
|
||||
title: Use Destructuring Assignment to Assign Variables from Nested Objects
|
||||
title: Use Atribuição de Desestruturação para Atribuir Variáveis de Objetos Aninhados
|
||||
challengeType: 1
|
||||
forumTopicId: 301214
|
||||
dashedName: use-destructuring-assignment-to-assign-variables-from-nested-objects
|
||||
@ -8,9 +8,9 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-nested-objects
|
||||
|
||||
# --description--
|
||||
|
||||
You can use the same principles from the previous two lessons to destructure values from nested objects.
|
||||
Você pode usar os mesmos princípios das últimas duas lições para desestruturar valores de objetos aninhados.
|
||||
|
||||
Using an object similar to previous examples:
|
||||
Usando um objeto similar aos exemplos anteriores:
|
||||
|
||||
```js
|
||||
const user = {
|
||||
@ -21,13 +21,13 @@ const user = {
|
||||
};
|
||||
```
|
||||
|
||||
Here's how to extract the values of object properties and assign them to variables with the same name:
|
||||
Aqui está como extrair valores de propriedades de objetos e atribuí-los a variáveis com o mesmo nome:
|
||||
|
||||
```js
|
||||
const { johnDoe: { age, email }} = user;
|
||||
```
|
||||
|
||||
And here's how you can assign an object properties' values to variables with different names:
|
||||
E aqui está como você pode atribuir o valor de uma propriedade de um objeto para variáveis com nomes diferentes:
|
||||
|
||||
```js
|
||||
const { johnDoe: { age: userAge, email: userEmail }} = user;
|
||||
@ -35,11 +35,11 @@ const { johnDoe: { age: userAge, email: userEmail }} = user;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `lowToday` and `highToday` the values of `today.low` and `today.high` from the `LOCAL_FORECAST` object.
|
||||
Substitua as duas atribuições com uma atribuição de desestruturação equivalente. Ainda deve ser atribuído às variáveis `lowToday` e `highToday` os valores de `today.low` e `today.high` do objeto `LOCAL_FORECAST`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should remove the ES5 assignment syntax.
|
||||
Você deve remover a sintaxe de atribuição do ES5.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `lowToday` variable.
|
||||
Você deve usar desestruturação para criar a variável `lowToday`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -58,7 +58,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `highToday` variable.
|
||||
Você deve usar desestruturação para criar a variável `highToday`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -68,7 +68,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`lowToday` should be equal to `64` and `highToday` should be equal to `77`.
|
||||
`lowToday` deve ser igual a `64` e `highToday` deve ser igual a `77`.
|
||||
|
||||
```js
|
||||
assert(lowToday === 64 && highToday === 77);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b89367417b2b2512b49
|
||||
title: Use Destructuring Assignment to Assign Variables from Objects
|
||||
title: Use Atribuição de Desestruturação para Atribuir Variáveis de Objetos
|
||||
challengeType: 1
|
||||
forumTopicId: 301215
|
||||
dashedName: use-destructuring-assignment-to-assign-variables-from-objects
|
||||
@ -8,29 +8,29 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-objects
|
||||
|
||||
# --description--
|
||||
|
||||
Destructuring allows you to assign a new variable name when extracting values. You can do this by putting the new name after a colon when assigning the value.
|
||||
Desestruturar o permite atribuir um novo nome de variável quando extrair valores. Você pode fazer isso ao colocar o novo nome após dois pontos quando atribuir o valor.
|
||||
|
||||
Using the same object from the last example:
|
||||
Usando o mesmo objeto do exemplo anterior:
|
||||
|
||||
```js
|
||||
const user = { name: 'John Doe', age: 34 };
|
||||
```
|
||||
|
||||
Here's how you can give new variable names in the assignment:
|
||||
Aqui está como você pode dar novos nomes a variáveis na atribuição:
|
||||
|
||||
```js
|
||||
const { name: userName, age: userAge } = user;
|
||||
```
|
||||
|
||||
You may read it as "get the value of `user.name` and assign it to a new variable named `userName`" and so on. The value of `userName` would be the string `John Doe`, and the value of `userAge` would be the number `34`.
|
||||
Você pode lê-lo como "pegue o valor de `user.name` e atribua-o a uma nova variável chamada `userName`" e assim em diante. O valor de `userName` seria a string `John Doe` e o valor de `userAge` seria o número `34`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `highToday` and `highTomorrow` the values of `today` and `tomorrow` from the `HIGH_TEMPERATURES` object.
|
||||
Substitua as duas atribuições com uma atribuição de desestruturação equivalente. Ainda deve ser atribuído às variáveis `highToday` e `highTomorrow` os valores de `today` e `tomorrow` do objeto `HIGH_TEMPERATURES`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should remove the ES5 assignment syntax.
|
||||
Você deve remover a sintaxe da atribuição ES5.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -39,7 +39,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `highToday` variable.
|
||||
Você deve usar desestruturação para criar a variável `highToday`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -49,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `highTomorrow` variable.
|
||||
Você deve usar desestruturação para criar a variável `highTomorrow`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -59,7 +59,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`highToday` should be equal to `77` and `highTomorrow` should be equal to `80`.
|
||||
`highToday` deve ser igual a `77` e `highTomorrow` deve ser igual a `80`.
|
||||
|
||||
```js
|
||||
assert(highToday === 77 && highTomorrow === 80);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cfa550e84205a357704ccb6
|
||||
title: Use Destructuring Assignment to Extract Values from Objects
|
||||
title: Use Atribuição de Desestruturação para Extrair Valores de Objetos
|
||||
challengeType: 1
|
||||
forumTopicId: 301216
|
||||
dashedName: use-destructuring-assignment-to-extract-values-from-objects
|
||||
@ -8,9 +8,9 @@ dashedName: use-destructuring-assignment-to-extract-values-from-objects
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Destructuring assignment</dfn> is special syntax introduced in ES6, for neatly assigning values taken directly from an object.
|
||||
<dfn>Atribuição de Desestruturação</dfn> é uma sintaxe especial introduzida na ES6, para atribuir nitidamente valores retirados diretamente de um objeto.
|
||||
|
||||
Consider the following ES5 code:
|
||||
Considere o seguinte código ES5:
|
||||
|
||||
```js
|
||||
const user = { name: 'John Doe', age: 34 };
|
||||
@ -19,27 +19,27 @@ const name = user.name;
|
||||
const age = user.age;
|
||||
```
|
||||
|
||||
`name` would have a value of the string `John Doe`, and `age` would have the number `34`.
|
||||
`name` teria o valor da string `John Doe` e `age` teria o número `34`.
|
||||
|
||||
Here's an equivalent assignment statement using the ES6 destructuring syntax:
|
||||
Aqui está uma instrução de atribuição equivalente usando a sintaxe de desestruturação ES6:
|
||||
|
||||
```js
|
||||
const { name, age } = user;
|
||||
```
|
||||
|
||||
Again, `name` would have a value of the string `John Doe`, and `age` would have the number `34`.
|
||||
Novamente, `name` teria o valor da string `John Doe` e `age` teria o número `34`.
|
||||
|
||||
Here, the `name` and `age` variables will be created and assigned the values of their respective values from the `user` object. You can see how much cleaner this is.
|
||||
Aqui, as variáveis `name` e `age` serão criadas e atribuídas a elas os valores de seus respectivos valores do objeto `user`. Você pode ver quão mais limpo é.
|
||||
|
||||
You can extract as many or few values from the object as you want.
|
||||
Você pode extrair quantos valores do objeto quanto você quer.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `today` and `tomorrow` the values of `today` and `tomorrow` from the `HIGH_TEMPERATURES` object.
|
||||
Substitua as duas atribuições com a atribuição de desestruturação equivalente. Ainda deve ser atribuído às valores `today` e `tomorrow` os valores de `today` e `tomorrow` do objeto `HIGH_TEMPERATURES`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should remove the ES5 assignment syntax.
|
||||
Você deve remover a sintaxe de atribuição do ES5.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -47,7 +47,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `today` variable.
|
||||
Você deve usar desestruturação para criar a variável `today`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -55,7 +55,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `tomorrow` variable.
|
||||
Você deve usar desestruturação para criar a variável `tomorrow`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -63,7 +63,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`today` should be equal to `77` and `tomorrow` should be equal to `80`.
|
||||
`today` deve ser igual a `77` e `tomorrow` deve ser igual a `80`.
|
||||
|
||||
```js
|
||||
assert(today === 77 && tomorrow === 80);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8a367417b2b2512b4d
|
||||
title: Use Destructuring Assignment to Pass an Object as a Function's Parameters
|
||||
title: Use Atribuição de Desestruturação para Passar um Objeto como Parâmetro de uma Função
|
||||
challengeType: 1
|
||||
forumTopicId: 301217
|
||||
dashedName: use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters
|
||||
@ -8,9 +8,9 @@ dashedName: use-destructuring-assignment-to-pass-an-object-as-a-functions-parame
|
||||
|
||||
# --description--
|
||||
|
||||
In some cases, you can destructure the object in a function argument itself.
|
||||
Em alguns casos, você pode desestruturar um objeto no próprio argumento da função.
|
||||
|
||||
Consider the code below:
|
||||
Considere o código abaixo:
|
||||
|
||||
```js
|
||||
const profileUpdate = (profileData) => {
|
||||
@ -19,7 +19,7 @@ const profileUpdate = (profileData) => {
|
||||
}
|
||||
```
|
||||
|
||||
This effectively destructures the object sent into the function. This can also be done in-place:
|
||||
Isso desestrutura efetivamente o objeto enviado para a função. Isso também pode ser feito no lugar:
|
||||
|
||||
```js
|
||||
const profileUpdate = ({ name, age, nationality, location }) => {
|
||||
@ -27,33 +27,33 @@ const profileUpdate = ({ name, age, nationality, location }) => {
|
||||
}
|
||||
```
|
||||
|
||||
When `profileData` is passed to the above function, the values are destructured from the function parameter for use within the function.
|
||||
Quando `profileData` é passado para a função acima, os valores são desestruturados do parâmetro da função para ser usado dentro da função.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use destructuring assignment within the argument to the function `half` to send only `max` and `min` inside the function.
|
||||
Use atribuição de desestruturação dentro do argumento para a função `half` para enviar apenas `max` e `min` para dentro da função.
|
||||
|
||||
# --hints--
|
||||
|
||||
`stats` should be an `object`.
|
||||
`stats` deve ser um `object`.
|
||||
|
||||
```js
|
||||
assert(typeof stats === 'object');
|
||||
```
|
||||
|
||||
`half(stats)` should be `28.015`
|
||||
`half(stats)` deve ser `28.015`
|
||||
|
||||
```js
|
||||
assert(half(stats) === 28.015);
|
||||
```
|
||||
|
||||
Destructuring should be used.
|
||||
Desestruturação deve ser usado.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/half=\({\w+,\w+}\)/));
|
||||
```
|
||||
|
||||
Destructured parameter should be used.
|
||||
Parâmetro desestruturado deve ser usado.
|
||||
|
||||
```js
|
||||
assert(!code.match(/stats\.max|stats\.min/));
|
||||
|
@ -1,7 +1,7 @@
|
||||
---
|
||||
id: 587d7b8a367417b2b2512b4c
|
||||
title: >-
|
||||
Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements
|
||||
Use Atribuição de Desestruturação com o Parâmetro Rest para Reatribuir Elementos de Array
|
||||
challengeType: 1
|
||||
forumTopicId: 301218
|
||||
dashedName: >-
|
||||
@ -10,9 +10,9 @@ dashedName: >-
|
||||
|
||||
# --description--
|
||||
|
||||
In some situations involving array destructuring, we might want to collect the rest of the elements into a separate array.
|
||||
Em algumas situações envolvendo um array desestruturado, podemos querer coletar o resto dos elementos em um array separado.
|
||||
|
||||
The result is similar to `Array.prototype.slice()`, as shown below:
|
||||
O resultado é similar a `Array.prototype.slice()`, como mostrado abaixo:
|
||||
|
||||
```js
|
||||
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
|
||||
@ -20,35 +20,35 @@ console.log(a, b);
|
||||
console.log(arr);
|
||||
```
|
||||
|
||||
The console would display the values `1, 2` and `[3, 4, 5, 7]`.
|
||||
O console exibiria os valores `1, 2` e `[3, 4, 5, 7]`.
|
||||
|
||||
Variables `a` and `b` take the first and second values from the array. After that, because of the rest parameter's presence, `arr` gets the rest of the values in the form of an array. The rest element only works correctly as the last variable in the list. As in, you cannot use the rest parameter to catch a subarray that leaves out the last element of the original array.
|
||||
As variáveis `a` e `b` pegam o primeiro e o segundo valores do array. Após isso, por causa da presença do parâmetro rest, `arr` pega o resto dos valores na forma de um array. O elemento rest só funciona corretamente como a última variável na lista. Como em, você não pode usar o parâmetro rest para capturar um subarray que deixa de fora o último elemento do array original.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use destructuring assignment with the rest parameter to perform an effective `Array.prototype.slice()` so that `arr` is a sub-array of the original array `source` with the first two elements omitted.
|
||||
Use atribuição de desestruturação com o parâmetro rest para executar `Array.prototype.slice()` de forma eficaz para que `arr` seja um sub array do array original `source` com os dois primeiros elementos omitidos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`arr` should be `[3,4,5,6,7,8,9,10]`
|
||||
`arr` deve ser `[3,4,5,6,7,8,9,10]`
|
||||
|
||||
```js
|
||||
assert(arr.every((v, i) => v === i + 3) && arr.length === 8);
|
||||
```
|
||||
|
||||
`source` should be `[1,2,3,4,5,6,7,8,9,10]`
|
||||
`source` deve ser `[1,2,3,4,5,6,7,8,9,10]`
|
||||
|
||||
```js
|
||||
assert(source.every((v, i) => v === i + 1) && source.length === 10);
|
||||
```
|
||||
|
||||
`Array.slice()` should not be used.
|
||||
`Array.slice()` não deve ser usado.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/slice/g));
|
||||
```
|
||||
|
||||
Destructuring on `list` should be used.
|
||||
Desestruturação na `list` deve ser usada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8c367417b2b2512b56
|
||||
title: Use export to Share a Code Block
|
||||
title: Use a exportação para compartilhar um Bloco de Código
|
||||
challengeType: 1
|
||||
forumTopicId: 301219
|
||||
dashedName: use-export-to-share-a-code-block
|
||||
@ -8,7 +8,7 @@ dashedName: use-export-to-share-a-code-block
|
||||
|
||||
# --description--
|
||||
|
||||
Imagine a file called `math_functions.js` that contains several functions related to mathematical operations. One of them is stored in a variable, `add`, that takes in two numbers and returns their sum. You want to use this function in several different JavaScript files. In order to share it with these other files, you first need to `export` it.
|
||||
Imagine um arquivo chamado `math_functions.js` que contém várias funções relacionadas a operações matemáticas. Uma delas é armazenada em uma variável, `add`, que recebe dois números e retorna a soma deles. Você quer usar essa função em diversos arquivos JavaScript diferentes. Para compartilhá-las com esses outros arquivos, você primeiro precisa exportá-las (`export`).
|
||||
|
||||
```js
|
||||
export const add = (x, y) => {
|
||||
@ -16,7 +16,7 @@ export const add = (x, y) => {
|
||||
}
|
||||
```
|
||||
|
||||
The above is a common way to export a single function, but you can achieve the same thing like this:
|
||||
Acima está uma forma comum de exportar uma única função, mas você pode alcançar a mesma coisa da seguinte forma:
|
||||
|
||||
```js
|
||||
const add = (x, y) => {
|
||||
@ -26,7 +26,7 @@ const add = (x, y) => {
|
||||
export { add };
|
||||
```
|
||||
|
||||
When you export a variable or function, you can import it in another file and use it without having to rewrite the code. You can export multiple things by repeating the first example for each thing you want to export, or by placing them all in the export statement of the second example, like this:
|
||||
Quando você exporta uma variável ou função, você pode importá-las em outro arquivo e usá-las sem ter de rescrever o código. Você pode exportar várias coisas ao repetir o primeiro exemplo para cada coisa que você queira exportar, ou ao colocar todas elas em uma instrução de export do segundo exemplo, da seguinte forma:
|
||||
|
||||
```js
|
||||
export { add, subtract };
|
||||
@ -34,11 +34,11 @@ export { add, subtract };
|
||||
|
||||
# --instructions--
|
||||
|
||||
There are two string-related functions in the editor. Export both of them using the method of your choice.
|
||||
Há duas funções relacionadas a string no editor. Exporte ambas usando o método de sua escolha.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should properly export `uppercaseString`.
|
||||
Você deve exportar corretamente `uppercaseString`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should properly export `lowercaseString`.
|
||||
Você deve exportar corretamente `lowercaseString`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8c367417b2b2512b54
|
||||
title: Use getters and setters to Control Access to an Object
|
||||
title: Use getters e setter para Controlar Acesso a um Objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301220
|
||||
dashedName: use-getters-and-setters-to-control-access-to-an-object
|
||||
@ -8,13 +8,13 @@ dashedName: use-getters-and-setters-to-control-access-to-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
You can obtain values from an object and set the value of a property within an object.
|
||||
Você pode obter valores de um objeto e definir o valor da propriedade dentro de um objeto.
|
||||
|
||||
These are classically called <dfn>getters</dfn> and <dfn>setters</dfn>.
|
||||
Esses são classicamente chamados de <dfn>getters</dfn> e <dfn>setters</dfn>.
|
||||
|
||||
Getter functions are meant to simply return (get) the value of an object's private variable to the user without the user directly accessing the private variable.
|
||||
Funções getter tem a finalidade de simplesmente retornar (get) o valor de uma variável privada de um objeto para o usuário sem que o usuário acesse diretamente a variável privada.
|
||||
|
||||
Setter functions are meant to modify (set) the value of an object's private variable based on the value passed into the setter function. This change could involve calculations, or even overwriting the previous value completely.
|
||||
Funções setter tem a finalidade de modificar, ou definir (set), o valor de uma variável privada de um objeto baseado no valor passado dentro da função setter. Essa mudança poderia envolver cálculos, ou até sobrescrever completamente o valor anterior.
|
||||
|
||||
```js
|
||||
class Book {
|
||||
@ -36,29 +36,29 @@ novel.writer = 'newAuthor';
|
||||
console.log(novel.writer);
|
||||
```
|
||||
|
||||
The console would display the strings `anonymous` and `newAuthor`.
|
||||
O console exibirá as strings `anonymous` e `newAuthor`.
|
||||
|
||||
Notice the syntax used to invoke the getter and setter. They do not even look like functions. Getters and setters are important because they hide internal implementation details.
|
||||
Note a sintaxe usada para invocar o getter e setter. Eles nem sequer se parecem com funções. Getters e setters são importantes porque escondem os detalhes internos da implementação.
|
||||
|
||||
**Note:** It is convention to precede the name of a private variable with an underscore (`_`). However, the practice itself does not make a variable private.
|
||||
**Nota:** É uma convenção preceder o nome de uma variável privada com um underscore (`_`). No entanto, essa prática por si só não torna uma variável privada.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `class` keyword to create a `Thermostat` class. The `constructor` accepts a Fahrenheit temperature.
|
||||
Use a palavra-chave `class` para criar a classe `Thermostat`. O `constructor` aceita uma temperatura Fahrenheit.
|
||||
|
||||
In the class, create a `getter` to obtain the temperature in Celsius and a `setter` to set the temperature in Celsius.
|
||||
Na classe, crie um `getter` para obter a temperatura em Celsius e um `setter` para definir a temperatura em Celsius.
|
||||
|
||||
Remember that `C = 5/9 * (F - 32)` and `F = C * 9.0 / 5 + 32`, where `F` is the value of temperature in Fahrenheit, and `C` is the value of the same temperature in Celsius.
|
||||
Lembre-se que `C = 5/9 * (F - 32)` e `F = C * 9.0 / 5 + 32`, aonde `F` é o valor da temperatura em Fahrenheit e `C` é o valor da mesma temperatura em Celsius.
|
||||
|
||||
**Note:** When you implement this, you will track the temperature inside the class in one scale, either Fahrenheit or Celsius.
|
||||
**Nota:** Quando você implementa isso, você irá rastrar a temperatura dentro da classe em uma escala, ou Fahrenheit ou Celsius.
|
||||
|
||||
This is the power of a getter and a setter. You are creating an API for another user, who can get the correct result regardless of which one you track.
|
||||
Esse é o poder de um getter e um setter. Você está criando uma API para outro uso, que pode pegar o resultado correto independente de qual está rastreando.
|
||||
|
||||
In other words, you are abstracting implementation details from the user.
|
||||
Em outras palavras, você está abstraindo detalhes de implementação do usuário.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Thermostat` should be a `class` with a defined `constructor` method.
|
||||
`Thermostat` deve ser uma `class` com um método `constructor` definido.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -67,13 +67,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`class` keyword should be used.
|
||||
A palavra-chave `class` deve ser usado.
|
||||
|
||||
```js
|
||||
assert(code.match(/class/g));
|
||||
```
|
||||
|
||||
`Thermostat` should be able to be instantiated.
|
||||
`Thermostat` deve ser possível de ser instanciado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -84,7 +84,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
When instantiated with a Fahrenheit value, `Thermostat` should set the correct `temperature`.
|
||||
Quando instanciado com um valor Fahrenheit, `Thermostat` deve definir a `temperature` correta.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -95,7 +95,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
A `getter` should be defined.
|
||||
Um `getter` deve ser definido.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -109,7 +109,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
A `setter` should be defined.
|
||||
Um `setter` deve ser definido.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -123,7 +123,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Calling the `setter` with a Celsius value should set the `temperature`.
|
||||
Chamando um `setter` com um valor Celsius deve definir a `temperature`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b88367417b2b2512b47
|
||||
title: Use the Rest Parameter with Function Parameters
|
||||
title: Use o Parâmetro Rest com Parâmetros de Função
|
||||
challengeType: 1
|
||||
forumTopicId: 301221
|
||||
dashedName: use-the-rest-parameter-with-function-parameters
|
||||
@ -8,9 +8,9 @@ dashedName: use-the-rest-parameter-with-function-parameters
|
||||
|
||||
# --description--
|
||||
|
||||
In order to help us create more flexible functions, ES6 introduces the <dfn>rest parameter</dfn> for function parameters. With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.
|
||||
Para nos ajuda a criar funções mais flexíveis, ES6 introduziu o <dfn>parâmetro rest</dfn> para parâmetros de funções. Com o parâmetro rest, você pode criar funções que recebem um número variável de argumentos. Esses argumentos são armazenados em um array que pode ser acessado depois dentro da função.
|
||||
|
||||
Check out this code:
|
||||
Verifique esse código:
|
||||
|
||||
```js
|
||||
function howMany(...args) {
|
||||
@ -20,41 +20,41 @@ console.log(howMany(0, 1, 2));
|
||||
console.log(howMany("string", null, [1, 2, 3], { }));
|
||||
```
|
||||
|
||||
The console would display the strings `You have passed 3 arguments.` and `You have passed 4 arguments.`.
|
||||
O console exibiria as strings `You have passed 3 arguments` e `You have passed 4 arguments.</codde>.</p>
|
||||
|
||||
The rest parameter eliminates the need to check the `args` array and allows us to apply `map()`, `filter()` and `reduce()` on the parameters array.
|
||||
<p spaces-before="0">O parâmetro rest elimina a necessidade de verificar o array <code>args` e nos permite usar `map()`, `filter()` e `reduce()` no array de parâmetros.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the function `sum` using the rest parameter in such a way that the function `sum` is able to take any number of arguments and return their sum.
|
||||
Modifique a função `sum` usando o parâmetro rest de tal forma que a função `sum` seja capaz de receber qualquer número de argumentos e retornar a soma deles.
|
||||
|
||||
# --hints--
|
||||
|
||||
The result of `sum(0,1,2)` should be 3
|
||||
O resultado de `sum(0,1,2)` deve ser 3
|
||||
|
||||
```js
|
||||
assert(sum(0, 1, 2) === 3);
|
||||
```
|
||||
|
||||
The result of `sum(1,2,3,4)` should be 10
|
||||
O resultado de `sum(1,2,3,4)` deve ser 10
|
||||
|
||||
```js
|
||||
assert(sum(1, 2, 3, 4) === 10);
|
||||
```
|
||||
|
||||
The result of `sum(5)` should be 5
|
||||
O resultado de `sum(5)` deve ser 5
|
||||
|
||||
```js
|
||||
assert(sum(5) === 5);
|
||||
```
|
||||
|
||||
The result of `sum()` should be 0
|
||||
O resultado de `sum()` deve ser 0
|
||||
|
||||
```js
|
||||
assert(sum() === 0);
|
||||
```
|
||||
|
||||
`sum` should be an arrow function which uses the rest parameter syntax (`...`) on the `args` parameter.
|
||||
`sum` deve ser uma arrow function que usa a sintaxe de parâmetro rest (`...`) no parâmetro `args`.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/sum=\(\.\.\.args\)=>/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b89367417b2b2512b48
|
||||
title: Use the Spread Operator to Evaluate Arrays In-Place
|
||||
title: Use o Operador Spread para Avaliar Arrays No Lugar
|
||||
challengeType: 1
|
||||
forumTopicId: 301222
|
||||
dashedName: use-the-spread-operator-to-evaluate-arrays-in-place
|
||||
@ -8,27 +8,27 @@ dashedName: use-the-spread-operator-to-evaluate-arrays-in-place
|
||||
|
||||
# --description--
|
||||
|
||||
ES6 introduces the <dfn>spread operator</dfn>, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected.
|
||||
ES6 introduz o <dfn>operador spread</dfn>, o qual nos permite expandir arrays e outras expresões no lugar aonde é esperado diversos parâmetros ou elementos.
|
||||
|
||||
The ES5 code below uses `apply()` to compute the maximum value in an array:
|
||||
O código em ES5 abaixo usa `apply()` para calcular o valor máximo de um array:
|
||||
|
||||
```js
|
||||
var arr = [6, 89, 3, 45];
|
||||
var maximus = Math.max.apply(null, arr);
|
||||
```
|
||||
|
||||
`maximus` would have a value of `89`.
|
||||
`maximus` teria o valor de `89`.
|
||||
|
||||
We had to use `Math.max.apply(null, arr)` because `Math.max(arr)` returns `NaN`. `Math.max()` expects comma-separated arguments, but not an array. The spread operator makes this syntax much better to read and maintain.
|
||||
Tivemos de usar `Math.max.apply(null, arr)` porque `Math.max(arr)` retorna `NaN`. `Math.max()` espera argumentos separados por vírgula, mas não um array. O operador spread torna essa sintaxe muito mais legível e mais fácil de manter.
|
||||
|
||||
```js
|
||||
const arr = [6, 89, 3, 45];
|
||||
const maximus = Math.max(...arr);
|
||||
```
|
||||
|
||||
`maximus` would have a value of `89`.
|
||||
`maximus` teria o valor de `89`.
|
||||
|
||||
`...arr` returns an unpacked array. In other words, it *spreads* the array. However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work:
|
||||
`...arr` retorna um array descompactado. Em outras palavras, ele *espalha (spreads)* o array. No entanto, o operador spread apenas funciona no local, como em um argumento para uma função ou em um array literal. O código a seguir não funcionará:
|
||||
|
||||
```js
|
||||
const spreaded = ...arr;
|
||||
@ -36,23 +36,23 @@ const spreaded = ...arr;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Copy all contents of `arr1` into another array `arr2` using the spread operator.
|
||||
Copie todo o conteúdo de `arr1` em outro array `arr2` usando o operador spread.
|
||||
|
||||
# --hints--
|
||||
|
||||
`arr2` should be correct copy of `arr1`.
|
||||
`arr2` deve ser uma cópia correta de `arr1`.
|
||||
|
||||
```js
|
||||
assert(arr2.every((v, i) => v === arr1[i]) && arr2.length);
|
||||
```
|
||||
|
||||
`...` spread operator should be used to duplicate `arr1`.
|
||||
O operador spread `...` deve ser usado para duplicar `arr1`.
|
||||
|
||||
```js
|
||||
assert(code.match(/Array\(\s*\.\.\.arr1\s*\)|\[\s*\.\.\.arr1\s*\]/));
|
||||
```
|
||||
|
||||
`arr2` should remain unchanged when `arr1` is changed.
|
||||
`arr2` deve continuar inalterado quando `arr1` é modificado=.
|
||||
|
||||
```js
|
||||
assert((arr1, arr2) => {
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b88367417b2b2512b44
|
||||
title: Write Arrow Functions with Parameters
|
||||
title: Escrever Funções de Seta com Parâmetros
|
||||
challengeType: 1
|
||||
forumTopicId: 301223
|
||||
dashedName: write-arrow-functions-with-parameters
|
||||
@ -8,49 +8,49 @@ dashedName: write-arrow-functions-with-parameters
|
||||
|
||||
# --description--
|
||||
|
||||
Just like a regular function, you can pass arguments into an arrow function.
|
||||
Assim como uma função normal, você pode passar argumentos para uma função de seta.
|
||||
|
||||
```js
|
||||
const doubler = (item) => item * 2;
|
||||
doubler(4);
|
||||
```
|
||||
|
||||
`doubler(4)` would return the value `8`.
|
||||
`doubler(4)` retornaria o valor `8`.
|
||||
|
||||
If an arrow function has a single parameter, the parentheses enclosing the parameter may be omitted.
|
||||
Se uma função de seta tiver um único parâmetro, os parênteses envolvendo o parâmetro podem ser omitidos.
|
||||
|
||||
```js
|
||||
const doubler = item => item * 2;
|
||||
```
|
||||
|
||||
It is possible to pass more than one argument into an arrow function.
|
||||
É possível passar mais de um argumento para uma função de seta.
|
||||
|
||||
```js
|
||||
const multiplier = (item, multi) => item * multi;
|
||||
multiplier(4, 2);
|
||||
```
|
||||
|
||||
`multiplier(4, 2)` would return the value `8`.
|
||||
`multiplier(4, 2)` retornaria o valor `8`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Rewrite the `myConcat` function which appends contents of `arr2` to `arr1` so that the function uses arrow function syntax.
|
||||
Reescreva a função `myConcat` que anexa conteúdo de `arr2` para `arr1` para que a função use sintaxe de arrow function.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should replace the `var` keyword.
|
||||
Você deve substituir a palavra-chave `var`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/var/g));
|
||||
```
|
||||
|
||||
`myConcat` should be a constant variable (by using `const`).
|
||||
`myConcat` deve ser uma variável constante (usando `const`).
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(getUserInput('index').match(/const\s+myConcat/g));
|
||||
```
|
||||
|
||||
`myConcat` should be an arrow function with two parameters
|
||||
`myConcat` deve ser uma função de seta com dois parâmetros
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -59,13 +59,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myConcat()` should return `[1, 2, 3, 4, 5]`.
|
||||
`meuConcat()` deve retornar `[1, 2, 3, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myConcat([1, 2], [3, 4, 5]), [1, 2, 3, 4, 5]);
|
||||
```
|
||||
|
||||
The `function` keyword should not be used.
|
||||
A palavra-chave `function` não deve ser usada.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/function/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8b367417b2b2512b50
|
||||
title: Write Concise Declarative Functions with ES6
|
||||
title: Escreva Declaração de Funções Concisas com ES6
|
||||
challengeType: 1
|
||||
forumTopicId: 301224
|
||||
dashedName: write-concise-declarative-functions-with-es6
|
||||
@ -8,7 +8,7 @@ dashedName: write-concise-declarative-functions-with-es6
|
||||
|
||||
# --description--
|
||||
|
||||
When defining functions within objects in ES5, we have to use the keyword `function` as follows:
|
||||
Ao definir funções dentro de objetos em ES5, nós temos de usar a palavra-chave `function` como se segue:
|
||||
|
||||
```js
|
||||
const person = {
|
||||
@ -19,7 +19,7 @@ const person = {
|
||||
};
|
||||
```
|
||||
|
||||
With ES6, you can remove the `function` keyword and colon altogether when defining functions in objects. Here's an example of this syntax:
|
||||
Com ES6, você pode remover a palavra-chave `function` e dois pontos ao definir funções em objetos. Aqui está um exemplo dessa sintaxe:
|
||||
|
||||
```js
|
||||
const person = {
|
||||
@ -32,17 +32,17 @@ const person = {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Refactor the function `setGear` inside the object `bicycle` to use the shorthand syntax described above.
|
||||
Refatore a função `setGear` dentro do objeto `bicycle` para usar a sintaxe curta descrita acima.
|
||||
|
||||
# --hints--
|
||||
|
||||
Traditional function expression should not be used.
|
||||
Expressão tradicional de função não deve ser usado.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!code.match(/function/));
|
||||
```
|
||||
|
||||
`setGear` should be a declarative function.
|
||||
`setGear` deve ser uma função declarativa.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -50,7 +50,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`bicycle.setGear(48)` should change the `gear` value to 48.
|
||||
`bicycle.setGear(48)` deve alterar o valor de `gear` para 48.
|
||||
|
||||
```js
|
||||
assert(new bicycle.setGear(48).gear === 48);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8a367417b2b2512b4f
|
||||
title: Write Concise Object Literal Declarations Using Object Property Shorthand
|
||||
title: Escreva Declarações Literais de Objetos Concisas usando a Forma Abreviada de Propriedade de Objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301225
|
||||
dashedName: write-concise-object-literal-declarations-using-object-property-shorthand
|
||||
@ -8,9 +8,9 @@ dashedName: write-concise-object-literal-declarations-using-object-property-shor
|
||||
|
||||
# --description--
|
||||
|
||||
ES6 adds some nice support for easily defining object literals.
|
||||
ES6 adiciona alguns suportes legais para facilmente definir literais de objetos.
|
||||
|
||||
Consider the following code:
|
||||
Considere o seguinte código:
|
||||
|
||||
```js
|
||||
const getMousePosition = (x, y) => ({
|
||||
@ -19,7 +19,7 @@ const getMousePosition = (x, y) => ({
|
||||
});
|
||||
```
|
||||
|
||||
`getMousePosition` is a simple function that returns an object containing two properties. ES6 provides the syntactic sugar to eliminate the redundancy of having to write `x: x`. You can simply write `x` once, and it will be converted to`x: x` (or something equivalent) under the hood. Here is the same function from above rewritten to use this new syntax:
|
||||
`getMousePosition` é uma função simples que retorna um objeto contendo duas propriedades. ES6 fornece o açúcar sintático para eliminar a redundância de ter de escrever `x: x`. Você pode simplesmente escrever `x` uma vez, e será convertido para `x: x` (ou algo equivalente). Aqui está a mesma função que acima rescrita para usar a nova sintaxe:
|
||||
|
||||
```js
|
||||
const getMousePosition = (x, y) => ({ x, y });
|
||||
@ -27,11 +27,11 @@ const getMousePosition = (x, y) => ({ x, y });
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use object property shorthand with object literals to create and return an object with `name`, `age` and `gender` properties.
|
||||
Use a abreviação de propriedade de objeto com literais de objeto para criar e retornar um objeto com as propriedades `name`, `age` e `gender`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`createPerson("Zodiac Hasbro", 56, "male")` should return `{name: "Zodiac Hasbro", age: 56, gender: "male"}`.
|
||||
`createPerson("Zodiac Hasbro", 56, "male")` deve retornar `{name: "Zodiac Hasbro", age: 56, gender: "male"}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -40,7 +40,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should not use `key:value`.
|
||||
Seu código deve usar `key:value`.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/:/g));
|
||||
|
Reference in New Issue
Block a user