chore: manual translations (#42811)
This commit is contained in:
committed by
GitHub
parent
a3395269a0
commit
c4fd49e5b7
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a77dbc43c33f39daa4429b4f
|
||||
title: Boo who
|
||||
title: Verdadeiro ou falso
|
||||
challengeType: 5
|
||||
forumTopicId: 16000
|
||||
dashedName: boo-who
|
||||
@ -8,67 +8,67 @@ dashedName: boo-who
|
||||
|
||||
# --description--
|
||||
|
||||
Check if a value is classified as a boolean primitive. Return `true` or `false`.
|
||||
Verifica se um valor é classificado como booleano primitivo. Retorna `true` ou `false`.
|
||||
|
||||
Boolean primitives are `true` and `false`.
|
||||
Primitivas booleanas são `true` e `false`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`booWho(true)` should return `true`.
|
||||
`booWho(true)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(true), true);
|
||||
```
|
||||
|
||||
`booWho(false)` should return `true`.
|
||||
`booWho(false)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(false), true);
|
||||
```
|
||||
|
||||
`booWho([1, 2, 3])` should return `false`.
|
||||
`booWho([1,2,3])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho([1, 2, 3]), false);
|
||||
```
|
||||
|
||||
`booWho([].slice)` should return `false`.
|
||||
`booWho([].slice)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho([].slice), false);
|
||||
```
|
||||
|
||||
`booWho({ "a": 1 })` should return `false`.
|
||||
`booWho({"a": 1})` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho({ a: 1 }), false);
|
||||
```
|
||||
|
||||
`booWho(1)` should return `false`.
|
||||
`booWho(1)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(1), false);
|
||||
```
|
||||
|
||||
`booWho(NaN)` should return `false`.
|
||||
`booWho(NaN)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho(NaN), false);
|
||||
```
|
||||
|
||||
`booWho("a")` should return `false`.
|
||||
`booWho("a")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('a'), false);
|
||||
```
|
||||
|
||||
`booWho("true")` should return `false`.
|
||||
`booWho("true")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('true'), false);
|
||||
```
|
||||
|
||||
`booWho("false")` should return `false`.
|
||||
`booWho("false")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(booWho('false'), false);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a9bd25c716030ec90084d8a1
|
||||
title: Chunky Monkey
|
||||
title: Macaco Robusto
|
||||
challengeType: 5
|
||||
forumTopicId: 16005
|
||||
dashedName: chunky-monkey
|
||||
@ -8,11 +8,11 @@ dashedName: chunky-monkey
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that splits an array (first argument) into groups the length of `size` (second argument) and returns them as a two-dimensional array.
|
||||
Escreva uma função que divida um array (primeiro argumento) em grupos de comprimento `size` (segundo argumento) e os retorne como um array bidimensional.
|
||||
|
||||
# --hints--
|
||||
|
||||
`chunkArrayInGroups(["a", "b", "c", "d"], 2)` should return `[["a", "b"], ["c", "d"]]`.
|
||||
`chunkArrayInGroups(["a", "b", "c", "d"], 2)` deve retornar `[["a", "b"], ["c", "d"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [
|
||||
@ -21,7 +21,7 @@ assert.deepEqual(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` should return `[[0, 1, 2], [3, 4, 5]]`.
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3)` deve retornar `[[0, 1, 2], [3, 4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [
|
||||
@ -30,7 +30,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` should return `[[0, 1], [2, 3], [4, 5]]`.
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2)` deve retornar `[[0, 1], [2, 3], [4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [
|
||||
@ -40,7 +40,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` should return `[[0, 1, 2, 3], [4, 5]]`.
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4)` deve retornar `[[0, 1, 2, 3], [4, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [
|
||||
@ -49,7 +49,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` should return `[[0, 1, 2], [3, 4, 5], [6]]`.
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3)` deve retornar `[[0, 1, 2], [3, 4, 5], [6]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [
|
||||
@ -59,7 +59,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` should return `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`.
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4)` deve retornar `[[0, 1, 2, 3], [4, 5, 6, 7], [8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [
|
||||
@ -69,7 +69,7 @@ assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4), [
|
||||
]);
|
||||
```
|
||||
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` should return `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`.
|
||||
`chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2)` deve retornar `[[0, 1], [2, 3], [4, 5], [6, 7], [8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: acda2fb1324d9b0fa741e6b5
|
||||
title: Confirm the Ending
|
||||
title: Confirme o final
|
||||
challengeType: 5
|
||||
forumTopicId: 16006
|
||||
dashedName: confirm-the-ending
|
||||
@ -8,31 +8,31 @@ dashedName: confirm-the-ending
|
||||
|
||||
# --description--
|
||||
|
||||
Check if a string (first argument, `str`) ends with the given target string (second argument, `target`).
|
||||
Verifique se uma string (primeiro argumento, `str`) termina com a sequência de caracteres de destino fornecida (segundo argumento, `target`).
|
||||
|
||||
This challenge *can* be solved with the `.endsWith()` method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.
|
||||
Este desafio *pode ser resolvido* com o método `.endsWith()`, que foi introduzido na ES2015. Mas para a finalidade deste desafio, gostaríamos que você usasse um dos métodos de substring JavaScript.
|
||||
|
||||
# --hints--
|
||||
|
||||
`confirmEnding("Bastian", "n")` should return `true`.
|
||||
`confirmEnding("Bastian","n")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Bastian', 'n') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Congratulation", "on")` should return `true`.
|
||||
`confirmEnding("Congratulation","on")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Congratulation', 'on') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Connor", "n")` should return `false`.
|
||||
`confirmEnding("Connor","n")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Connor', 'n') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification")` should return `false`.
|
||||
`confirmEnding("Walking on water and developing software from a specifaction are easy if both are frozen","specification")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,31 +43,31 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`confirmEnding("He has to give me a new name", "name")` should return `true`.
|
||||
`confirmEnding("He has to give me a new name","name")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('He has to give me a new name', 'name') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "same")` should return `true`.
|
||||
`confirmEnding("Open sesame","same")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'same') === true);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "sage")` should return `false`.
|
||||
`confirmEnding("Open sesame", "sage")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'sage') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("Open sesame", "game")` should return `false`.
|
||||
`confirmEnding("Open sesame","game")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Open sesame', 'game') === false);
|
||||
```
|
||||
|
||||
`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")` should return `false`.
|
||||
`confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -78,13 +78,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`confirmEnding("Abstraction", "action")` should return `true`.
|
||||
`confirmEnding("Abstraction", "action")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(confirmEnding('Abstraction', 'action') === true);
|
||||
```
|
||||
|
||||
Your code should not use the built-in method `.endsWith()` to solve the challenge.
|
||||
Seu código não deve usar o método embutido `.endsWith()` para resolver o desafio.
|
||||
|
||||
```js
|
||||
assert(!/\.endsWith\(.*?\)\s*?;?/.test(code) && !/\['endsWith'\]/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b3
|
||||
title: Convert Celsius to Fahrenheit
|
||||
title: Converta Celsius para Fahrenheit
|
||||
challengeType: 1
|
||||
forumTopicId: 16806
|
||||
dashedName: convert-celsius-to-fahrenheit
|
||||
@ -8,43 +8,43 @@ dashedName: convert-celsius-to-fahrenheit
|
||||
|
||||
# --description--
|
||||
|
||||
The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times `9/5`, plus `32`.
|
||||
O algoritmo para converter de Celsius para Fahrenheit é a temperatura em Celsius vezes `9/5`, mais `32`.
|
||||
|
||||
You are given a variable `celsius` representing a temperature in Celsius. Use the variable `fahrenheit` already defined and assign it the Fahrenheit temperature equivalent to the given Celsius temperature. Use the algorithm mentioned above to help convert the Celsius temperature to Fahrenheit.
|
||||
Você tem uma variável `celsius` representando uma temperatura em Celsius. Use a variável `fahrenheit` já definida e atribua a ela a temperatura equivalente à temperatura Celsius indicada. Use o algoritmo mencionado acima para ajudar a converter a temperatura Celsius para Fahrenheit.
|
||||
|
||||
# --hints--
|
||||
|
||||
`convertToF(0)` should return a number
|
||||
`convertToF(0)` deve retornar um número
|
||||
|
||||
```js
|
||||
assert(typeof convertToF(0) === 'number');
|
||||
```
|
||||
|
||||
`convertToF(-30)` should return a value of `-22`
|
||||
`convertToF(-30)` deve retornar um valor de `-22`
|
||||
|
||||
```js
|
||||
assert(convertToF(-30) === -22);
|
||||
```
|
||||
|
||||
`convertToF(-10)` should return a value of `14`
|
||||
`convertToF(-10)` deve retornar um valor de `14`
|
||||
|
||||
```js
|
||||
assert(convertToF(-10) === 14);
|
||||
```
|
||||
|
||||
`convertToF(0)` should return a value of `32`
|
||||
`convertToF(0)` deve retornar um valor de `32`
|
||||
|
||||
```js
|
||||
assert(convertToF(0) === 32);
|
||||
```
|
||||
|
||||
`convertToF(20)` should return a value of `68`
|
||||
`convertToF(20)` deve retornar um valor de `68`
|
||||
|
||||
```js
|
||||
assert(convertToF(20) === 68);
|
||||
```
|
||||
|
||||
`convertToF(30)` should return a value of `86`
|
||||
`convertToF(30)` deve retornar um valor de `86`
|
||||
|
||||
```js
|
||||
assert(convertToF(30) === 86);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a302f7aae1aa3152a5b413bc
|
||||
title: Factorialize a Number
|
||||
title: Fatore um número
|
||||
challengeType: 5
|
||||
forumTopicId: 16013
|
||||
dashedName: factorialize-a-number
|
||||
@ -8,43 +8,43 @@ dashedName: factorialize-a-number
|
||||
|
||||
# --description--
|
||||
|
||||
Return the factorial of the provided integer.
|
||||
Retorne o fatorial do inteiro fornecido.
|
||||
|
||||
If the integer is represented with the letter `n`, a factorial is the product of all positive integers less than or equal to `n`.
|
||||
Se o inteiro é representado com a letra `n`, o fatorial é o produto de todos os inteiros positivos menor ou igual a `n`.
|
||||
|
||||
Factorials are often represented with the shorthand notation `n!`
|
||||
Fatoriais são frequentemente representados com notação abreviada `n!`
|
||||
|
||||
For example: `5! = 1 * 2 * 3 * 4 * 5 = 120`
|
||||
Por exemplo: `5! = 1 * 2 * 3 * 4 * 5 = 120`
|
||||
|
||||
Only integers greater than or equal to zero will be supplied to the function.
|
||||
Apenas números inteiros maiores ou iguais a zero serão fornecidos para a função.
|
||||
|
||||
# --hints--
|
||||
|
||||
`factorialize(5)` should return a number.
|
||||
`factorialize(5)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof factorialize(5) === 'number');
|
||||
```
|
||||
|
||||
`factorialize(5)` should return `120`.
|
||||
`factorialize(5)` deve retornar `120`.
|
||||
|
||||
```js
|
||||
assert(factorialize(5) === 120);
|
||||
```
|
||||
|
||||
`factorialize(10)` should return `3628800`.
|
||||
`factorialize(10)` deve retornar `3628800`.
|
||||
|
||||
```js
|
||||
assert(factorialize(10) === 3628800);
|
||||
```
|
||||
|
||||
`factorialize(20)` should return `2432902008176640000`.
|
||||
`factorialize(20)` deve retornar `2432902008176640000`.
|
||||
|
||||
```js
|
||||
assert(factorialize(20) === 2432902008176640000);
|
||||
```
|
||||
|
||||
`factorialize(0)` should return `1`.
|
||||
`factorialize(0)` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert(factorialize(0) === 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: adf08ec01beb4f99fc7a68f2
|
||||
title: Falsy Bouncer
|
||||
title: Removendo falsos
|
||||
challengeType: 5
|
||||
forumTopicId: 16014
|
||||
dashedName: falsy-bouncer
|
||||
@ -8,33 +8,33 @@ dashedName: falsy-bouncer
|
||||
|
||||
# --description--
|
||||
|
||||
Remove all falsy values from an array.
|
||||
Remover todos os valores falsos de um array.
|
||||
|
||||
Falsy values in JavaScript are `false`, `null`, `0`, `""`, `undefined`, and `NaN`.
|
||||
Valores falsos (falsy) em JavaScript são `false`, `null`, `0`, `""`, `undefined`, e `NaN`.
|
||||
|
||||
Hint: Try converting each value to a Boolean.
|
||||
Dica: tente converter cada valor para um booleano.
|
||||
|
||||
# --hints--
|
||||
|
||||
`bouncer([7, "ate", "", false, 9])` should return `[7, "ate", 9]`.
|
||||
`bouncer([7, "ate", "", false, 9])` deve retornar `[7, "ate", 9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([7, 'ate', '', false, 9]), [7, 'ate', 9]);
|
||||
```
|
||||
|
||||
`bouncer(["a", "b", "c"])` should return `["a", "b", "c"]`.
|
||||
`bouncer(["a", "b", "c"])` deve retornar `["a", "b", "c"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer(['a', 'b', 'c']), ['a', 'b', 'c']);
|
||||
```
|
||||
|
||||
`bouncer([false, null, 0, NaN, undefined, ""])` should return `[]`.
|
||||
`bouncer([false, null, 0, NaN, undefined, ""])` deve retornar `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([false, null, 0, NaN, undefined, '']), []);
|
||||
```
|
||||
|
||||
`bouncer([null, NaN, 1, 2, undefined])` should return `[1, 2]`.
|
||||
`bouncer([null, NaN, 1, 2, undefined])` deve retornar `[1, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bouncer([null, NaN, 1, 2, undefined]), [1, 2]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a26cbbe9ad8655a977e1ceb5
|
||||
title: Find the Longest Word in a String
|
||||
title: Encontre a palavra mais longa em uma String
|
||||
challengeType: 5
|
||||
forumTopicId: 16015
|
||||
dashedName: find-the-longest-word-in-a-string
|
||||
@ -8,13 +8,13 @@ dashedName: find-the-longest-word-in-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
Return the length of the longest word in the provided sentence.
|
||||
Retornar o comprimento da palavra mais comprida na frase fornecida.
|
||||
|
||||
Your response should be a number.
|
||||
Sua resposta deve ser um número.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` should return a number.
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -24,7 +24,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` should return `6`.
|
||||
`findLongestWordLength("The quick brown fox jumped over the lazy dog")` deve retornar `6`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -32,19 +32,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("May the force be with you")` should return `5`.
|
||||
`findLongestWordLength("May the force be with you")` deve retornar `5`.
|
||||
|
||||
```js
|
||||
assert(findLongestWordLength('May the force be with you') === 5);
|
||||
```
|
||||
|
||||
`findLongestWordLength("Google do a barrel roll")` should return `6`.
|
||||
`findLongestWordLength("Google do a barrel roll")` deve retornar `6`.
|
||||
|
||||
```js
|
||||
assert(findLongestWordLength('Google do a barrel roll') === 6);
|
||||
```
|
||||
|
||||
`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` should return `8`.
|
||||
`findLongestWordLength("What is the average airspeed velocity of an unladen swallow")` deve retornar `8`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,7 +54,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` should return `19`.
|
||||
`findLongestWordLength("What if we try a super-long word such as otorhinolaryngology")` deve retornar `19`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a6e40f1041b06c996f7b2406
|
||||
title: Finders Keepers
|
||||
title: Achado Não é Roubado
|
||||
challengeType: 5
|
||||
forumTopicId: 16016
|
||||
dashedName: finders-keepers
|
||||
@ -8,11 +8,11 @@ dashedName: finders-keepers
|
||||
|
||||
# --description--
|
||||
|
||||
Create a function that looks through an array `arr` and returns the first element in it that passes a 'truth test'. This means that given an element `x`, the 'truth test' is passed if `func(x)` is `true`. If no element passes the test, return `undefined`.
|
||||
Crie uma função que olhe através do array `arr` e retorne o primeiro elemento dentro do array que passe pelo 'teste de verdade' ('truth test'). Isso significa que dado um elemento `x`, o 'teste de verdade' é verdadeiro se `func(x)` é `true`. Se nenhum elemento passa no test, retorna `undefined`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` should return `8`.
|
||||
`findElement([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; })` deve retornar `8`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -23,7 +23,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` should return `undefined`.
|
||||
`findElement([1, 3, 5, 9], function(num) { return num % 2 === 0; })` deve retornar `undefined`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: af2170cad53daa0770fabdea
|
||||
title: Mutations
|
||||
title: Mutações
|
||||
challengeType: 5
|
||||
forumTopicId: 16025
|
||||
dashedName: mutations
|
||||
@ -8,83 +8,83 @@ dashedName: mutations
|
||||
|
||||
# --description--
|
||||
|
||||
Return `true` if the string in the first element of the array contains all of the letters of the string in the second element of the array.
|
||||
Retorne `true` se a string no primeiro elemento do array contém todas as letras da string no segundo elemento do array.
|
||||
|
||||
For example, `["hello", "Hello"]`, should return `true` because all of the letters in the second string are present in the first, ignoring case.
|
||||
Por exemplo, `["hello", "Hello"]`, deve retornar `true` porque todas as letras na segunda string estão presentes no primeiro, ignorando diferenças entre maiúsculos e minúsculos.
|
||||
|
||||
The arguments `["hello", "hey"]` should return `false` because the string `hello` does not contain a `y`.
|
||||
Os argumentos `["hello","hey"]` deve retornar `false` porque a string `hello` não contém o caracter `y`.
|
||||
|
||||
Lastly, `["Alien", "line"]`, should return `true` because all of the letters in `line` are present in `Alien`.
|
||||
Por último, `["Alien", "line"]`, deve retornar `true` porque todas as letras em `line` estão presente em `Alien`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mutation(["hello", "hey"])` should return `false`.
|
||||
`mutation(["hello", "hey"])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'hey']) === false);
|
||||
```
|
||||
|
||||
`mutation(["hello", "Hello"])` should return `true`.
|
||||
`mutation(["hello","Hello"])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'Hello']) === true);
|
||||
```
|
||||
|
||||
`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` should return `true`.
|
||||
`mutation(["zyxwvutsrqponmlkjihgfedcba", "qrstu"])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['zyxwvutsrqponmlkjihgfedcba', 'qrstu']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Mary", "Army"])` should return `true`.
|
||||
`mutation(["Mary", "Army"])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Mary', 'Army']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Mary", "Aarmy"])` should return `true`.
|
||||
`mutation(["Mary", "Aarmy"])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Mary', 'Aarmy']) === true);
|
||||
```
|
||||
|
||||
`mutation(["Alien", "line"])` should return `true`.
|
||||
`mutation(["Alien", "line"])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Alien', 'line']) === true);
|
||||
```
|
||||
|
||||
`mutation(["floor", "for"])` should return `true`.
|
||||
`mutation(["floor", "for"])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['floor', 'for']) === true);
|
||||
```
|
||||
|
||||
`mutation(["hello", "neo"])` should return `false`.
|
||||
`mutation(["hello", "neo"])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['hello', 'neo']) === false);
|
||||
```
|
||||
|
||||
`mutation(["voodoo", "no"])` should return `false`.
|
||||
`mutation(["voodoo", "no"])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['voodoo', 'no']) === false);
|
||||
```
|
||||
|
||||
`mutation(["ate", "date"])` should return `false`.
|
||||
`mutation(["ate", "date"])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['ate', 'date']) === false);
|
||||
```
|
||||
|
||||
`mutation(["Tiger", "Zebra"])` should return `false`.
|
||||
`mutation(["Tiger", "Zebra"])` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Tiger', 'Zebra']) === false);
|
||||
```
|
||||
|
||||
`mutation(["Noel", "Ole"])` should return `true`.
|
||||
`mutation(["Noel", "Ole"])` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(mutation(['Noel', 'Ole']) === true);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: afcc8d540bea9ea2669306b6
|
||||
title: Repeat a String Repeat a String
|
||||
title: Repita uma String Repita uma String
|
||||
challengeType: 5
|
||||
forumTopicId: 16041
|
||||
dashedName: repeat-a-string-repeat-a-string
|
||||
@ -8,53 +8,53 @@ dashedName: repeat-a-string-repeat-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
Repeat a given string `str` (first argument) for `num` times (second argument). Return an empty string if `num` is not a positive number. For the purpose of this challenge, do *not* use the built-in `.repeat()` method.
|
||||
Repita uma string passada `str` (primeiro argumento), `num` vezes (segundo argumento). Retorne uma string vazia se `num` não for um número positivo. Para o propósito do desafio, *Não* use o método embutido `.repeat()`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`repeatStringNumTimes("*", 3)` should return the string `***`.
|
||||
`repeatStringNumTimes("*", 3)` deve retornar a string `***`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('*', 3) === '***');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 3)` should return the string `abcabcabc`.
|
||||
`repeatStringNumTimes("abc", 3)` deve retornar a string `abcabcabc`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 3) === 'abcabcabc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 4)` should return the string `abcabcabcabc`.
|
||||
`repeatStringNumTimes("abc", 4)` deve retornar a `abcabcabcabc`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 4) === 'abcabcabcabc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 1)` should return the string `abc`.
|
||||
`repeatStringNumTimes("abc", 1)` deve retornar a string `abc`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 1) === 'abc');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("*", 8)` should return the string `********`.
|
||||
`repeatStringNumTimes("*", 8)` deve retornar a `********`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('*', 8) === '********');
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", -2)` should return an empty string (`""`).
|
||||
`repeatStringNumTimes("abc", -2)` deve retornar uma string vazia (`""`).
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', -2) === '');
|
||||
```
|
||||
|
||||
The built-in `repeat()` method should not be used.
|
||||
O método embutido `repeat()` não deve ser usada.
|
||||
|
||||
```js
|
||||
assert(!/\.repeat/g.test(code));
|
||||
```
|
||||
|
||||
`repeatStringNumTimes("abc", 0)` should return `""`.
|
||||
`repeatStringNumTimes("abc", 0)` deve retornar `""`.
|
||||
|
||||
```js
|
||||
assert(repeatStringNumTimes('abc', 0) === '');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a789b3483989747d63b0e427
|
||||
title: Return Largest Numbers in Arrays
|
||||
title: Retorne os Maior Número em Arrays
|
||||
challengeType: 5
|
||||
forumTopicId: 16042
|
||||
dashedName: return-largest-numbers-in-arrays
|
||||
@ -8,13 +8,13 @@ dashedName: return-largest-numbers-in-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
|
||||
Retorna um array que consiste do maior número de cada sub-array fornecido. Por simplicidade, o array fornecido conterá exatamente 4 sub-arrays.
|
||||
|
||||
Remember, you can iterate through an array with a simple for loop, and access each member with array syntax `arr[i]`.
|
||||
Lembre-se, você pode iterar através de um array com um loop simples, e acesse cada membro com a sintaxe de array `arr[i]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])` should return an array.
|
||||
`largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -27,7 +27,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` should return `[27, 5, 39, 1001]`.
|
||||
`largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]])` deve retornar `[27, 5, 39, 1001]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -41,7 +41,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` should return `[9, 35, 97, 1000000]`.
|
||||
`largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]])` deve retornar `[9, 35, 97, 1000000]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -55,7 +55,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])` should return `[25, 48, 21, -3]`.
|
||||
`largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]])` deve retornar `[25, 48, 21, -3]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a202eed8fc186c8434cb6d61
|
||||
title: Reverse a String
|
||||
title: Inverter uma String
|
||||
challengeType: 5
|
||||
forumTopicId: 16043
|
||||
dashedName: reverse-a-string
|
||||
@ -8,33 +8,33 @@ dashedName: reverse-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
Reverse the provided string.
|
||||
Inverta a string fornecida.
|
||||
|
||||
You may need to turn the string into an array before you can reverse it.
|
||||
Você pode ter que transformar a string em um array antes de você poder inverter.
|
||||
|
||||
Your result must be a string.
|
||||
Seu resultado deve ser uma string.
|
||||
|
||||
# --hints--
|
||||
|
||||
`reverseString("hello")` should return a string.
|
||||
`reverseString("hello")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof reverseString('hello') === 'string');
|
||||
```
|
||||
|
||||
`reverseString("hello")` should return the string `olleh`.
|
||||
`reverseString("hello")` deve retornar a string `olleh`.
|
||||
|
||||
```js
|
||||
assert(reverseString('hello') === 'olleh');
|
||||
```
|
||||
|
||||
`reverseString("Howdy")` should return the string `ydwoH`.
|
||||
`reverseString("Howdy")` deve retornar a string `ydwoH`.
|
||||
|
||||
```js
|
||||
assert(reverseString('Howdy') === 'ydwoH');
|
||||
```
|
||||
|
||||
`reverseString("Greetings from Earth")` should return the string `htraE morf sgniteerG`.
|
||||
`reverseString("Greetings from Earth")` deve retornar a string `htraE morf sgniteerG`.
|
||||
|
||||
```js
|
||||
assert(reverseString('Greetings from Earth') === 'htraE morf sgniteerG');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 579e2a2c335b9d72dd32e05c
|
||||
title: Slice and Splice
|
||||
title: Fatiar e Emendar
|
||||
challengeType: 5
|
||||
forumTopicId: 301148
|
||||
dashedName: slice-and-splice
|
||||
@ -8,29 +8,29 @@ dashedName: slice-and-splice
|
||||
|
||||
# --description--
|
||||
|
||||
You are given two arrays and an index.
|
||||
Você está recebendo dois arrays e um índice.
|
||||
|
||||
Copy each element of the first array into the second array, in order.
|
||||
Copie cada elemento da primeira matriz para a segunda matriz, em ordem.
|
||||
|
||||
Begin inserting elements at index `n` of the second array.
|
||||
Comece inserindo elementos no índice `n` do segundo array.
|
||||
|
||||
Return the resulting array. The input arrays should remain the same after the function runs.
|
||||
Retorne o array resultante. Os arrays recebidos devem permanecer os mesmos após a função ser executada.
|
||||
|
||||
# --hints--
|
||||
|
||||
`frankenSplice([1, 2, 3], [4, 5], 1)` should return `[4, 1, 2, 3, 5]`.
|
||||
`frankenSplice([1, 2, 3], [4, 5], 1)` deve retornar `[4, 1, 2, 3, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice([1, 2, 3], [4, 5], 1), [4, 1, 2, 3, 5]);
|
||||
```
|
||||
|
||||
`frankenSplice([1, 2], ["a", "b"], 1)` should return `["a", 1, 2, "b"]`.
|
||||
`frankenSplice([1, 2], ["a", "b"], 1)` deve retornar `["a", 1, 2, "b"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice(testArr1, testArr2, 1), ['a', 1, 2, 'b']);
|
||||
```
|
||||
|
||||
`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` should return `["head", "shoulders", "claw", "tentacle", "knees", "toes"]`.
|
||||
`frankenSplice(["claw", "tentacle"], ["head", "shoulders", "knees", "toes"], 2)` deve retornar `["head", "shoulders", "claw", "tentacle", "knees", "toes"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -43,20 +43,20 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
All elements from the first array should be added to the second array in their original order.
|
||||
Todos os elementos do primeiro array devem ser adicionados no segundo array em suas ordens originais.
|
||||
|
||||
```js
|
||||
assert.deepEqual(frankenSplice([1, 2, 3, 4], [], 0), [1, 2, 3, 4]);
|
||||
```
|
||||
|
||||
The first array should remain the same after the function runs.
|
||||
O primeiro array deve permanecer o mesmo após a função ser executada.
|
||||
|
||||
```js
|
||||
frankenSplice(testArr1, testArr2, 1);
|
||||
assert.deepEqual(testArr1, [1, 2]);
|
||||
```
|
||||
|
||||
The second array should remain the same after the function runs.
|
||||
O segundo array deve permanecer o mesmo após a função ser executada.
|
||||
|
||||
```js
|
||||
frankenSplice(testArr1, testArr2, 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: ab6137d4e35944e21037b769
|
||||
title: Title Case a Sentence
|
||||
title: Capitalização de Título de uma Frase
|
||||
challengeType: 5
|
||||
forumTopicId: 16088
|
||||
dashedName: title-case-a-sentence
|
||||
@ -8,31 +8,31 @@ dashedName: title-case-a-sentence
|
||||
|
||||
# --description--
|
||||
|
||||
Return the provided string with the first letter of each word capitalized. Make sure the rest of the word is in lower case.
|
||||
Retorne a string fornecida com a primeira letra de cada palavra em maiúscula. Certifique-se de que o resto da palavra esteja em minúsculo.
|
||||
|
||||
For the purpose of this exercise, you should also capitalize connecting words like `the` and `of`.
|
||||
Para o propósito desse exercício, você também deve capitalizar as palavras conectoras como `the` e `of`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`titleCase("I'm a little tea pot")` should return a string.
|
||||
`titleCase("I'm a little tea pot")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof titleCase("I'm a little tea pot") === 'string');
|
||||
```
|
||||
|
||||
`titleCase("I'm a little tea pot")` should return the string `I'm A Little Tea Pot`.
|
||||
`titleCase("I'm a little tea pot")` deve retornar a string `I'm A Little Tea Pot`.
|
||||
|
||||
```js
|
||||
assert(titleCase("I'm a little tea pot") === "I'm A Little Tea Pot");
|
||||
```
|
||||
|
||||
`titleCase("sHoRt AnD sToUt")` should return the string `Short And Stout`.
|
||||
`titleCase("sHoRt AnD sToUt")` deve retornar a string `Short And Stout`.
|
||||
|
||||
```js
|
||||
assert(titleCase('sHoRt AnD sToUt') === 'Short And Stout');
|
||||
```
|
||||
|
||||
`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` should return the string `Here Is My Handle Here Is My Spout`.
|
||||
`titleCase("HERE IS MY HANDLE HERE IS MY SPOUT")` deve retornar a string `Here Is My Handle Here Is My Spout`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: ac6993d51946422351508a41
|
||||
title: Truncate a String
|
||||
title: Truncar uma String
|
||||
challengeType: 5
|
||||
forumTopicId: 16089
|
||||
dashedName: truncate-a-string
|
||||
@ -8,11 +8,11 @@ dashedName: truncate-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
Truncate a string (first argument) if it is longer than the given maximum string length (second argument). Return the truncated string with a `...` ending.
|
||||
Truncar uma string (primeiro argumento) se ela for maior que o comprimento máximo da string (segundo argumento). Retorne a string truncada com `...` (reticências) ao final.
|
||||
|
||||
# --hints--
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", 8)` should return the string `A-tisket...`.
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", 8)` deve retornar a string `A-tisket...`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -21,7 +21,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("Peter Piper picked a peck of pickled peppers", 11)` should return the string `Peter Piper...`.
|
||||
`truncateString("Peter Piper picked a peck of pickled peppers", 11)` deve retornar a string `Peter Piper...`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` should return the string `A-tisket a-tasket A green and yellow basket`.
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length)` deve retornar a string `A-tisket a-tasket A green and yellow basket`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,7 +41,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` should return the string `A-tisket a-tasket A green and yellow basket`.
|
||||
`truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2)` deve retornar a string `A-tisket a-tasket A green and yellow basket`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -52,13 +52,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`truncateString("A-", 1)` should return the string `A...`.
|
||||
`truncateString("A-", 1)` deve retornar a string `A...`.
|
||||
|
||||
```js
|
||||
assert(truncateString('A-', 1) === 'A...');
|
||||
```
|
||||
|
||||
`truncateString("Absolutely Longer", 2)` should return the string `Ab...`.
|
||||
`truncateString("Absolutely Longer", 2)` deve retornar a string `Ab...`.
|
||||
|
||||
```js
|
||||
assert(truncateString('Absolutely Longer', 2) === 'Ab...');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: a24c1a4622e3c05097f71d67
|
||||
title: Where do I Belong
|
||||
title: Aonde eu pertenço
|
||||
challengeType: 5
|
||||
forumTopicId: 16094
|
||||
dashedName: where-do-i-belong
|
||||
@ -8,105 +8,105 @@ dashedName: where-do-i-belong
|
||||
|
||||
# --description--
|
||||
|
||||
Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.
|
||||
Retorne o menor índice aonde um valor (segundo argumento) deve ser inserido no array (primeiro argumento) assim que tenha sido ordenado. O valor retornado deve ser um número.
|
||||
|
||||
For example, `getIndexToIns([1,2,3,4], 1.5)` should return `1` because it is greater than `1` (index 0), but less than `2` (index 1).
|
||||
Por exemplo, `getIndexToIns([1,2,3,4], 1.5)` deve retornar `1` porque é maior que `1` (índice 0), mas menor que `2` (índice 1).
|
||||
|
||||
Likewise, `getIndexToIns([20,3,5], 19)` should return `2` because once the array has been sorted it will look like `[3,5,20]` and `19` is less than `20` (index 2) and greater than `5` (index 1).
|
||||
Assim como, `getIndexToIns([20,3,5], 19)` deve retornar `2` pois uma vez que o array foi sorteado irá se parecer como `[3,5,20]` e `19` é menor que `20` (índice 2) e maior que `5` (índice 1).
|
||||
|
||||
# --hints--
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` should return `3`.
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` deve retornar `3`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([10, 20, 30, 40, 50], 35) === 3);
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` should return a number.
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 35)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 35) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` should return `2`.
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` deve retornar `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([10, 20, 30, 40, 50], 30) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` should return a number.
|
||||
`getIndexToIns([10, 20, 30, 40, 50], 30)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([10, 20, 30, 40, 50], 30) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([40, 60], 50)` should return `1`.
|
||||
`getIndexToIns([40, 60], 50)` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([40, 60], 50) === 1);
|
||||
```
|
||||
|
||||
`getIndexToIns([40, 60], 50)` should return a number.
|
||||
`getIndexToIns([40, 60], 50)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([40, 60], 50) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([3, 10, 5], 3)` should return `0`.
|
||||
`getIndexToIns([3, 10, 5], 3)` deve retornar `0`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([3, 10, 5], 3) === 0);
|
||||
```
|
||||
|
||||
`getIndexToIns([3, 10, 5], 3)` should return a number.
|
||||
`getIndexToIns([3, 10, 5], 3)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([3, 10, 5], 3) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` should return `2`.
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` deve retornar `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([5, 3, 20, 3], 5) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` should return a number.
|
||||
`getIndexToIns([5, 3, 20, 3], 5)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([5, 3, 20, 3], 5) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 20, 10], 19)` should return `2`.
|
||||
`getIndexToIns([2, 20, 10], 19)` deve retornar `2`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([2, 20, 10], 19) === 2);
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 20, 10], 19)` should return a number.
|
||||
`getIndexToIns([2, 20, 10], 19)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([2, 20, 10], 19) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 5, 10], 15)` should return `3`.
|
||||
`getIndexToIns([2, 5, 10], 15)` deve retornar `3`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([2, 5, 10], 15) === 3);
|
||||
```
|
||||
|
||||
`getIndexToIns([2, 5, 10], 15)` should return a number.
|
||||
`getIndexToIns([2, 5, 10], 15)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([2, 5, 10], 15) === 'number');
|
||||
```
|
||||
|
||||
`getIndexToIns([], 1)` should return `0`.
|
||||
`getIndexToIns([], 1)` deve retornar `0`.
|
||||
|
||||
```js
|
||||
assert(getIndexToIns([], 1) === 0);
|
||||
```
|
||||
|
||||
`getIndexToIns([], 1)` should return a number.
|
||||
`getIndexToIns([], 1)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof getIndexToIns([], 1) === 'number');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a661e0f1068aca922b3ef17
|
||||
title: Access an Array's Contents Using Bracket Notation
|
||||
title: Acesse o Conteúdo de uma Lista Utilizando a Notação de Colchetes
|
||||
challengeType: 1
|
||||
forumTopicId: 301149
|
||||
dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
@ -8,55 +8,55 @@ dashedName: access-an-arrays-contents-using-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
The fundamental feature of any data structure is, of course, the ability to not only store data, but to be able to retrieve that data on command. So, now that we've learned how to create an array, let's begin to think about how we can access that array's information.
|
||||
A funcionalidade fundamental de qualquer estrutura de dados é, evidentemente, não só a capacidade de armazenar informação, como também a possibilidade de acessar esta informação quando necessário. Então, agora que aprendemos como criar um vetor, vamos começar a pensar em como podemos acessar as informações desse vetor.
|
||||
|
||||
When we define a simple array as seen below, there are 3 items in it:
|
||||
Quando definimos uma matriz simples como vista abaixo, existem 3 itens nela:
|
||||
|
||||
```js
|
||||
let ourArray = ["a", "b", "c"];
|
||||
```
|
||||
|
||||
In an array, each array item has an <dfn>index</dfn>. This index doubles as the position of that item in the array, and how you reference it. However, it is important to note, that JavaScript arrays are <dfn>zero-indexed</dfn>, meaning that the first element of an array is actually at the ***zeroth*** position, not the first. In order to retrieve an element from an array we can enclose an index in brackets and append it to the end of an array, or more commonly, to a variable which references an array object. This is known as <dfn>bracket notation</dfn>. For example, if we want to retrieve the `a` from `ourArray` and assign it to a variable, we can do so with the following code:
|
||||
Em um array, cada item do array possui um <dfn>índice </dfn>. Esse índice possui dois papéis, é a posição daquele item no array e como você o referencia. No entanto, é importante notar que arrays em JavaScript são <dfn>indexados a zero</dfn>, o que significa que o primeiro elemento do array está, na verdade, na posição ***zero***, e não na primeira. Para recuperar um elemento de um array, nós podemos ao final de um array adicionar um índice encapsulado com colchetes (por exemplo [0]), ou mais comumente, no final de uma variável que faz referência a um objeto array. Isso é conhecido como <dfn>notação de colchetes</dfn>. Por exemplo, se queremos recuperar o `a` de um array `ourArray` e atribuir a uma variável, nós podemos fazer isso com o código a seguir:
|
||||
|
||||
```js
|
||||
let ourVariable = ourArray[0];
|
||||
```
|
||||
|
||||
Now `ourVariable` has the value of `a`.
|
||||
Agora `ourVariable` possui o valor de `a`.
|
||||
|
||||
In addition to accessing the value associated with an index, you can also *set* an index to a value using the same notation:
|
||||
Além de acessar o valor associado ao índice, você também pode *definir* um índice para um valor usando a mesma notação:
|
||||
|
||||
```js
|
||||
ourArray[1] = "not b anymore";
|
||||
```
|
||||
|
||||
Using bracket notation, we have now reset the item at index 1 from the string `b`, to `not b anymore`. Now `ourArray` is `["a", "not b anymore", "c"]`.
|
||||
Usando a notação de colchetes, agora nos redefinimos o item no índice 1, alterando a string `b`, para `not b anymore`. Agora `ourArray` é `["a", "not b anymore", "c"]`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In order to complete this challenge, set the 2nd position (index `1`) of `myArray` to anything you want, besides the letter `b`.
|
||||
A fim de concluir esse desafio, defina a segunda posição (index `1`) do `myArray` como qualquer coisa que deseja, exceto a letra `b`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myArray[0]` should be equal to the letter `a`
|
||||
`myArray[0]` deve ser igual à letra `a`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[0], 'a');
|
||||
```
|
||||
|
||||
`myArray[1]` should not be equal to the letter `b`
|
||||
`myArray[1]` não deve ser igual à letra `b`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(myArray[1], 'b');
|
||||
```
|
||||
|
||||
`myArray[2]` should be equal to the letter `c`
|
||||
`myArray[2]` deve ser igual à letra `c`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[2], 'c');
|
||||
```
|
||||
|
||||
`myArray[3]` should be equal to the letter `d`
|
||||
`myArray[3]` deve ser igual à letra `d`
|
||||
|
||||
```js
|
||||
assert.strictEqual(myArray[3], 'd');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1a
|
||||
title: Access Property Names with Bracket Notation
|
||||
title: Acesse Nomes de Propriedades com Notação de Colchetes
|
||||
challengeType: 1
|
||||
forumTopicId: 301150
|
||||
dashedName: access-property-names-with-bracket-notation
|
||||
@ -8,28 +8,28 @@ dashedName: access-property-names-with-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that our `foods` object is being used in a program for a supermarket cash register. We have some function that sets the `selectedFood` and we want to check our `foods` object for the presence of that food. This might look like:
|
||||
No primeiro desafio, nós mencionamos o uso da notação de colchetes como uma forma de acessar valores das propriedades usando a avaliação de uma variável. Por exemplo, imagine que nosso objeto `foods` está sendo usado em um programa para a caixa-registradora de um supermercado. Nós temos algumas funções que definem `selectedFood` e nós queremos checar a presença da `selectedFood` em nosso objeto `foods`. Isso pode parecer assim:
|
||||
|
||||
```js
|
||||
let selectedFood = getCurrentFood(scannedItem);
|
||||
let inventory = foods[selectedFood];
|
||||
```
|
||||
|
||||
This code will evaluate the value stored in the `selectedFood` variable and return the value of that key in the `foods` object, or `undefined` if it is not present. Bracket notation is very useful because sometimes object properties are not known before runtime or we need to access them in a more dynamic way.
|
||||
Esse código irá avaliar o valor armazenado na variável `selectedFood` e retorna o valor daquela chave no objeto `foods`, ou `undefined` se não estiver presente. Notação de colchetes é muito útil porque às vezes as propriedades de um objeto não são conhecidas antes da execução ou nós precisamos acessá-las de uma forma mais dinâmica.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We've defined a function, `checkInventory`, which receives a scanned item as an argument. Return the current value of the `scannedItem` key in the `foods` object. You can assume that only valid keys will be provided as an argument to `checkInventory`.
|
||||
Nós definimos uma função, `checkInventory`, a qual recebe um item escaneado como argumento. Retornar o valor atual da chave `scannedItem` no objeto `foods`. Você pode assumir que apenas chaves válidas serão fornecidas como um argumento para `checkInventory`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`checkInventory` should be a function.
|
||||
`checkInventory` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert.strictEqual(typeof checkInventory, 'function');
|
||||
```
|
||||
|
||||
The `foods` object should have only the following key-value pairs: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
|
||||
O objeto `foods` deve ter apenas as duplas de chaves e valores a seguir: `apples: 25`, `oranges: 32`, `plums: 28`, `bananas: 13`, `grapes: 35`, `strawberries: 27`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(foods, {
|
||||
@ -42,19 +42,19 @@ assert.deepEqual(foods, {
|
||||
});
|
||||
```
|
||||
|
||||
`checkInventory("apples")` should return `25`.
|
||||
`checkInventory("apples")` deve retornar `25`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('apples'), 25);
|
||||
```
|
||||
|
||||
`checkInventory("bananas")` should return `13`.
|
||||
`checkInventory("bananas")` deve retornar `13`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('bananas'), 13);
|
||||
```
|
||||
|
||||
`checkInventory("strawberries")` should return `27`.
|
||||
`checkInventory("strawberries")` deve retornar `27`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(checkInventory('strawberries'), 27);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0e
|
||||
title: Add Items to an Array with push() and unshift()
|
||||
title: Adicione itens em um Array com push() e unshift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301151
|
||||
dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
@ -8,9 +8,9 @@ dashedName: add-items-to-an-array-with-push-and-unshift
|
||||
|
||||
# --description--
|
||||
|
||||
An array's length, like the data types it can contain, is not fixed. Arrays can be defined with a length of any number of elements, and elements can be added or removed over time; in other words, arrays are <dfn>mutable</dfn>. In this challenge, we will look at two methods with which we can programmatically modify an array: `Array.push()` and `Array.unshift()`.
|
||||
O comprimento de um array, como os tipos de dados que pode conter, não são fixos. Arrays podem ser definidos com um comprimento de qualquer número de elementos e elementos podem ser adicionados e removidos ao decorrer do tempo; em outras palavras, arrays são <dfn>mutáveis</dfn>. Nesse desafio, nós olharemos dois métodos com os quais podemos modificar programaticamente um array: `Array.push()` e `Array.unshift()`.
|
||||
|
||||
Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the `push()` method adds elements to the end of an array, and `unshift()` adds elements to the beginning. Consider the following:
|
||||
Ambos os métodos recebem 1 ou mais elementos como parâmetros e adiciona esses elementos ao array no qual o método está sendo chamado; o método `push()` adiciona elementos ao final do array, e `unshift()` adiciona no início. Considere o seguinte:
|
||||
|
||||
```js
|
||||
let twentyThree = 'XXIII';
|
||||
@ -19,21 +19,21 @@ let romanNumerals = ['XXI', 'XXII'];
|
||||
romanNumerals.unshift('XIX', 'XX');
|
||||
```
|
||||
|
||||
`romanNumerals` would have the value `['XIX', 'XX', 'XXI', 'XXII']`.
|
||||
`romanNumerals` teria os valores `['XIX', 'XX', 'XXI', 'XXII']`.
|
||||
|
||||
```js
|
||||
romanNumerals.push(twentyThree);
|
||||
```
|
||||
|
||||
`romanNumerals` would have the value `['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`. Notice that we can also pass variables, which allows us even greater flexibility in dynamically modifying our array's data.
|
||||
`romanNumerals` teria os valores `['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`. Note que nós também podemos passar variáveis, as quais nos permitem uma flexibilidade ainda maior na modificação dinâmica dos dados de nosso array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `mixedNumbers`, which we are passing an array as an argument. Modify the function by using `push()` and `unshift()` to add `'I', 2, 'three'` to the beginning of the array and `7, 'VIII', 9` to the end so that the returned array contains representations of the numbers 1-9 in order.
|
||||
Nos definimos uma função, `mixedNumbers`, na qual estamos passando o array como um argumento. Modifique a função usando `push()` e `unshift()` para adicionar `'1', 2, 'three'` no início do array e `7, 'VIII', 9` ao final para que o array retornado contenha a representação dos números de 1 a 9 em ordem.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mixedNumbers(["IV", 5, "six"])` should now return `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
|
||||
`mixedNumbers(["IV", 5, "six"])` agora deve retornar `["I", 2, "three", "IV", 5, "six", 7, "VIII", 9]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
@ -49,13 +49,13 @@ assert.deepEqual(mixedNumbers(['IV', 5, 'six']), [
|
||||
]);
|
||||
```
|
||||
|
||||
The `mixedNumbers` function should utilize the `push()` method
|
||||
A função `mixedNumbers` deve usar o método `push()`
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.push/));
|
||||
```
|
||||
|
||||
The `mixedNumbers` function should utilize the `unshift()` method
|
||||
A função `mixedNumbers` deve usar o método `unshift()`
|
||||
|
||||
```js
|
||||
assert(mixedNumbers.toString().match(/\.unshift/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b3367417b2b2512b11
|
||||
title: Add Items Using splice()
|
||||
title: Adicione Itens Usando splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301152
|
||||
dashedName: add-items-using-splice
|
||||
@ -8,7 +8,7 @@ dashedName: add-items-using-splice
|
||||
|
||||
# --description--
|
||||
|
||||
Remember in the last challenge we mentioned that `splice()` can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.
|
||||
Se lembra que no último desafio mencionamos que `splice()` pode receber até três parâmetros? Bem, você pode usar o terceiro parâmetro, composto por um ou mais elementos, para adicioná-los ao array. Isso pode ser incrivelmente útil para mudar rapidamente um elemento, ou um conjunto de elementos, para outro.
|
||||
|
||||
```js
|
||||
const numbers = [10, 11, 12, 12, 15];
|
||||
@ -19,17 +19,17 @@ numbers.splice(startIndex, amountToDelete, 13, 14);
|
||||
console.log(numbers);
|
||||
```
|
||||
|
||||
The second occurrence of `12` is removed, and we add `13` and `14` at the same index. The `numbers` array would now be `[ 10, 11, 12, 13, 14, 15 ]`.
|
||||
A segunda ocorrência de `12` é removida, e adicionamos `13` e `14` no mesmo índice. O array `numbers` agora seria `[ 10, 11, 12, 13, 14, 15 ]`.
|
||||
|
||||
Here, we begin with an array of numbers. Then, we pass the following to `splice()`: The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note that there can be any number of elements (separated by commas) following `amountToDelete`, each of which gets inserted.
|
||||
Aqui, começamos com um array de números. Em seguida, passamos o seguinte para `splice()`: O índice no qual começar a deletar os elementos (3), o número de elementos a serem deletados (1) e os argumentos restantes (13, 14) serão inseridos com início no mesmo índice. Note que três pode ser qualquer número de elementos (separado por vírgulas) seguindo `amountToDelete`, cada um dos quais são inseridos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `htmlColorNames`, which takes an array of HTML colors as an argument. Modify the function using `splice()` to remove the first two elements of the array and add `'DarkSalmon'` and `'BlanchedAlmond'` in their respective places.
|
||||
Definimos uma função, `htmlColorNames`, a qual recebe um array de cores HTML como argumento. Modifique a função usando `splice()` para remover os dois primeiros elementos do array e adicionar `'DarkSalmon'` e `'BlanchedAlmond'` em seus respectivos lugares.
|
||||
|
||||
# --hints--
|
||||
|
||||
`htmlColorNames` should return `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
|
||||
`htmlColorNames` deve retornar `["DarkSalmon", "BlanchedAlmond", "LavenderBlush", "PaleTurquoise", "FireBrick"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -50,19 +50,19 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
The `htmlColorNames` function should utilize the `splice()` method
|
||||
A função `htmlColorNames` deve utilizar o método `splice()`
|
||||
|
||||
```js
|
||||
assert(/.splice/.test(code));
|
||||
```
|
||||
|
||||
You should not use `shift()` or `unshift()`.
|
||||
Você não deve usar `shift()` ou `unshift()`.
|
||||
|
||||
```js
|
||||
assert(!/shift|unshift/.test(code));
|
||||
```
|
||||
|
||||
You should not use array bracket notation.
|
||||
Você não deve usar a notação de colchetes de array.
|
||||
|
||||
```js
|
||||
assert(!/\[\d\]\s*=/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b18
|
||||
title: Add Key-Value Pairs to JavaScript Objects
|
||||
title: Adicione Pares de Chave-Valor a objetos JavaScript
|
||||
challengeType: 1
|
||||
forumTopicId: 301153
|
||||
dashedName: add-key-value-pairs-to-javascript-objects
|
||||
@ -8,7 +8,7 @@ dashedName: add-key-value-pairs-to-javascript-objects
|
||||
|
||||
# --description--
|
||||
|
||||
At their most basic, objects are just collections of <dfn>key-value</dfn> pairs. In other words, they are pieces of data (<dfn>values</dfn>) mapped to unique identifiers called <dfn>properties</dfn> (<dfn>keys</dfn>). Take a look at an example:
|
||||
Em suas formas mais básicas, objetos são apenas coleções de pares de <dfn>chave-valor</dfn>. Em outras palavras, eles são pedaços de dados (<dfn>valores</dfn>) mapeados para identificadores únicos chamados <dfn>propriedades</dfn> (<dfn>chaves</dfn>). Dê uma olhada no exemplo:
|
||||
|
||||
```js
|
||||
const tekkenCharacter = {
|
||||
@ -18,19 +18,19 @@ const tekkenCharacter = {
|
||||
};
|
||||
```
|
||||
|
||||
The above code defines a Tekken video game character object called `tekkenCharacter`. It has three properties, each of which map to a specific value. If you want to add an additional property, such as "origin", it can be done by assigning `origin` to the object:
|
||||
O código acima define um objeto de caractere de jogo Tekken chamado `tekkenCharacter`. Tem três propriedades, em que cada uma é mapeada para um valor específico. Se você quer adicionar uma propriedade adicional, como "origin", pode ser feito ao atribuir `origin` ao objeto:
|
||||
|
||||
```js
|
||||
tekkenCharacter.origin = 'South Korea';
|
||||
```
|
||||
|
||||
This uses dot notation. If you were to observe the `tekkenCharacter` object, it will now include the `origin` property. Hwoarang also had distinct orange hair. You can add this property with bracket notation by doing:
|
||||
Isso usa notação de ponto. Se você observar o objeto `tekkenCharacter`, agora incluirá a propriedade `origin`. Hwoarang também tinha distintos cabelos laranja. Você pode adicionar essa propriedade com notação de colchetes fazendo:
|
||||
|
||||
```js
|
||||
tekkenCharacter['hair color'] = 'dyed orange';
|
||||
```
|
||||
|
||||
Bracket notation is required if your property has a space in it or if you want to use a variable to name the property. In the above case, the property is enclosed in quotes to denote it as a string and will be added exactly as shown. Without quotes, it will be evaluated as a variable and the name of the property will be whatever value the variable is. Here's an example with a variable:
|
||||
A notação de colchete é necessária se sua propriedade tem um espaço nele ou se você deseja usar uma variável para nomear a propriedade. No caso acima, a propriedade está entre aspas para denotá-la como uma string e será adicionada exatamente como mostrada. Sem aspas, ele será avaliado como uma variável e o nome da propriedade será qualquer valor que a variável seja. Aqui está um exemplo com uma variável:
|
||||
|
||||
```js
|
||||
const eyes = 'eye color';
|
||||
@ -38,7 +38,7 @@ const eyes = 'eye color';
|
||||
tekkenCharacter[eyes] = 'brown';
|
||||
```
|
||||
|
||||
After adding all the examples, the object will look like this:
|
||||
Após adicionar todos os exemplos, o objeto ficará assim:
|
||||
|
||||
```js
|
||||
{
|
||||
@ -53,35 +53,35 @@ After adding all the examples, the object will look like this:
|
||||
|
||||
# --instructions--
|
||||
|
||||
A `foods` object has been created with three entries. Using the syntax of your choice, add three more entries to it: `bananas` with a value of `13`, `grapes` with a value of `35`, and `strawberries` with a value of `27`.
|
||||
O objeto `foods` foi criado com três entradas. Usando a sintaxe de sua escolha, adicione mais três entradas a ele: `bananas` com um valor de `13`, `uvas` com um valor de `35` e `morangos` com um valor de `27`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`foods` should be an object.
|
||||
`foods` deve ser um objeto.
|
||||
|
||||
```js
|
||||
assert(typeof foods === 'object');
|
||||
```
|
||||
|
||||
The `foods` object should have a key `bananas` with a value of `13`.
|
||||
O objeto `foods` deve ter a chave `bananas` com o valor de `13`.
|
||||
|
||||
```js
|
||||
assert(foods.bananas === 13);
|
||||
```
|
||||
|
||||
The `foods` object should have a key `grapes` with a value of `35`.
|
||||
O objeto `foods` deve ter a chave `grapes` com o valor de `35`.
|
||||
|
||||
```js
|
||||
assert(foods.grapes === 35);
|
||||
```
|
||||
|
||||
The `foods` object should have a key `strawberries` with a value of `27`.
|
||||
O objeto `foods` deve ter a chave `strawberries` com o valor de `35`.
|
||||
|
||||
```js
|
||||
assert(foods.strawberries === 27);
|
||||
```
|
||||
|
||||
The key-value pairs should be set using dot or bracket notation.
|
||||
Os pares de chave-valor devem serem definidos usando a notação de ponto ou de colchetes.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b14
|
||||
title: Check For The Presence of an Element With indexOf()
|
||||
title: Verifique a Presença de um Elemento com indexOf()
|
||||
challengeType: 1
|
||||
forumTopicId: 301154
|
||||
dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
@ -8,9 +8,9 @@ dashedName: check-for-the-presence-of-an-element-with-indexof
|
||||
|
||||
# --description--
|
||||
|
||||
Since arrays can be changed, or *mutated*, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, `indexOf()`, that allows us to quickly and easily check for the presence of an element on an array. `indexOf()` takes an element as a parameter, and when called, it returns the position, or index, of that element, or `-1` if the element does not exist on the array.
|
||||
Já que arrays podem ser alterados, ou *mutadas*, a qualquer momentos, não há garantia de onde um pedaço de dado estará em um determinado array, ou se esse elemento se quer existe. Felizmente, JavaScript nos fornece com outro método embutido, `indexOf()`, que nos permite rapidamente e facilmente checar pela presença de um elemento em um array. `indexOf()` recebe um elemento como parâmetro, e quando chamado, retorna a posição, ou índice, daquele elemento, ou `-1` se o elemento não existe no array.
|
||||
|
||||
For example:
|
||||
Por exemplo:
|
||||
|
||||
```js
|
||||
let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];
|
||||
@ -20,21 +20,21 @@ fruits.indexOf('oranges');
|
||||
fruits.indexOf('pears');
|
||||
```
|
||||
|
||||
`indexOf('dates')` returns `-1`, `indexOf('oranges')` returns `2`, and `indexOf('pears')` returns `1` (the first index at which each element exists).
|
||||
`indexOf('dates')` retorna `-1`, `indexOf('oranges')` retorna `2` e `indexOf('pears')` retorna `1` (o primeiro índice no qual cada elemento existe).
|
||||
|
||||
# --instructions--
|
||||
|
||||
`indexOf()` can be incredibly useful for quickly checking for the presence of an element on an array. We have defined a function, `quickCheck`, that takes an array and an element as arguments. Modify the function using `indexOf()` so that it returns `true` if the passed element exists on the array, and `false` if it does not.
|
||||
`indexOf()` pode ser incrivelmente útil para verificar rapidamente a presença de um elemento em um array. Definimos uma função, `quickCheck`, que recebe um array e um elemento como argumentos. Modifique a função usando `indexOf()` para que retorne `true` se o elemento passado existe no array, e`false` caso não exista.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `quickCheck` function should return a boolean (`true` or `false`), not a string (`"true"` or `"false"`)
|
||||
A função `quickCheck` deve retornar um booleano (`true` ou `false`), e não uma string (`"true"` ou `"false"`)
|
||||
|
||||
```js
|
||||
assert.isBoolean(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms'));
|
||||
```
|
||||
|
||||
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` should return `false`
|
||||
`quickCheck(["squash", "onions", "shallots"], "mushrooms")` deve retornar `false`
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -43,7 +43,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck(["onions", "squash", "shallots"], "onions")` should return `true`
|
||||
`quickCheck(["onions", "squash", "shallots"], "onions")` deve retornar `true`
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -52,19 +52,19 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`quickCheck([3, 5, 9, 125, 45, 2], 125)` should return `true`
|
||||
`quickCheck([3, 5, 9, 125, 45, 2], 125)` deve retornar `true`
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([3, 5, 9, 125, 45, 2], 125), true);
|
||||
```
|
||||
|
||||
`quickCheck([true, false, false], undefined)` should return `false`
|
||||
`quickCheck([true, false, false], undefined)` deve retornar `false`
|
||||
|
||||
```js
|
||||
assert.strictEqual(quickCheck([true, false, false], undefined), false);
|
||||
```
|
||||
|
||||
The `quickCheck` function should utilize the `indexOf()` method
|
||||
A função `quickCheck` deve utilizar o método `indexOf()`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(quickCheck.toString().search(/\.indexOf\(/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1c
|
||||
title: Check if an Object has a Property
|
||||
title: Verifique se um Objeto tem uma Propriedade
|
||||
challengeType: 1
|
||||
forumTopicId: 301155
|
||||
dashedName: check-if-an-object-has-a-property
|
||||
@ -8,22 +8,22 @@ dashedName: check-if-an-object-has-a-property
|
||||
|
||||
# --description--
|
||||
|
||||
Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the `hasOwnProperty()` method and the other uses the `in` keyword. If we have an object `users` with a property of `Alan`, we could check for its presence in either of the following ways:
|
||||
Agora podemos adicionar, modificar e remover as chaves dos objetos. Mas e se apenas quiséssemos saber se um objeto tem uma propriedade específica? O JavaScript nos fornece duas maneiras diferentes de fazer isso. Um usa o método `hasOwnProperty()` e o outro usa a palavra-chave `in`. Se tivermos um objeto `usuários` com uma propriedade de `Alan`, poderíamos verificar a sua presença de qualquer uma das seguintes maneiras:
|
||||
|
||||
```js
|
||||
users.hasOwnProperty('Alan');
|
||||
'Alan' in users;
|
||||
```
|
||||
|
||||
Both of these would return `true`.
|
||||
Ambos esses retornariam `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Finish writing the function so that it returns true if the object passed to it contains all four names, `Alan`, `Jeff`, `Sarah` and `Ryan` and returns false otherwise.
|
||||
Termine de escrever a função para que ela retorne verdadeiro se o objeto passado a ela contiver todos os quatro nomes, `Alan`, `Jeff`, `Sarah` e `Ryan` e retorna falso caso contrário.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `users` object should not be accessed directly
|
||||
O objeto `users` não deve ser acessado diretamente
|
||||
|
||||
```js
|
||||
|
||||
@ -31,7 +31,7 @@ assert(code.match(/users/gm).length <= 2)
|
||||
|
||||
```
|
||||
|
||||
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
|
||||
O objeto `users` deve conter apenas as chaves `Alan`, `Jeff`, `Sarah` e `Ryan`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,13 +43,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The function `isEveryoneHere` should return `true` if `Alan`, `Jeff`, `Sarah`, and `Ryan` are properties on the object passed to it.
|
||||
A função `isEveryoneHere` deve retornar `true` se `Alan`, `Jeff`, `Sarah`, e `Ryan` forem propriedades do objeto passado como argumento.
|
||||
|
||||
```js
|
||||
assert(isEveryoneHere(users) === true);
|
||||
```
|
||||
|
||||
The function `isEveryoneHere` should return `false` if `Alan` is not a property on the object passed to it.
|
||||
A função `isEveryoneHere` deve retornar `false` se `Alan` não for uma propriedade do objeto passado como argumento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -60,7 +60,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The function `isEveryoneHere` should return `false` if `Jeff` is not a property on the object passed to it.
|
||||
A função `isEveryoneHere` deve retornar `false` se `Jeff` não for uma propriedade no objeto passado como argumento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -71,7 +71,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The function `isEveryoneHere` should return `false` if `Sarah` is not a property on the object passed to it.
|
||||
A função `isEveryoneHere` deve retornar `false` se `Sarah` não for uma propriedade do objeto passado como argumento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -82,7 +82,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The function `isEveryoneHere` should return `false` if `Ryan` is not a property on the object passed to it.
|
||||
A função `isEveryoneHere` deve retornar `false` se `Ryan` não for uma propriedade do objeto passado como argumento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -119,7 +119,7 @@ let users = {
|
||||
|
||||
function isEveryoneHere(userObj) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b17
|
||||
title: Combine Arrays with the Spread Operator
|
||||
title: Combinar Arrays com o Operador Spread
|
||||
challengeType: 1
|
||||
forumTopicId: 301156
|
||||
dashedName: combine-arrays-with-the-spread-operator
|
||||
@ -8,7 +8,7 @@ dashedName: combine-arrays-with-the-spread-operator
|
||||
|
||||
# --description--
|
||||
|
||||
Another huge advantage of the <dfn>spread</dfn> operator is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:
|
||||
Outra grande vantagem do operador <dfn>spread</dfn> é a capacidade de combinar arrays, ou para inserir todos os elementos de um array em outro, em qualquer índice. Com sintaxe mais tradicional, podemos concatenar arrays, mas isso só nos permite combinar arrays no final de um e no início de outro. A sintaxe do spread torna a seguinte operação extremamente simples:
|
||||
|
||||
```js
|
||||
let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
|
||||
@ -16,23 +16,23 @@ let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
|
||||
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];
|
||||
```
|
||||
|
||||
`thatArray` would have the value `['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']`.
|
||||
`thatArray` teria o valor `['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander']`.
|
||||
|
||||
Using spread syntax, we have just achieved an operation that would have been more complex and more verbose had we used traditional methods.
|
||||
Usando a sintaxe de spread, acabamos de conseguir uma operação que teria sido mais complexa e mais verbosa se tivéssemos utilizado métodos tradicionais.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function `spreadOut` that returns the variable `sentence`. Modify the function using the <dfn>spread</dfn> operator so that it returns the array `['learning', 'to', 'code', 'is', 'fun']`.
|
||||
Definimos uma função `spreadOut` que retorna a variável `sentença`. Modifique a função usando o operador <dfn>spread</dfn> para que ele retorne o array `['learning', 'to', 'code', 'is', 'fun']`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`spreadOut` should return `["learning", "to", "code", "is", "fun"]`
|
||||
`spreadOut` deve retornar `["learning", "to", "code", "is", "fun"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(spreadOut(), ['learning', 'to', 'code', 'is', 'fun']);
|
||||
```
|
||||
|
||||
The `spreadOut` function should utilize spread syntax
|
||||
A função `spreadOut` deve utilizar a sintaxe spread
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(spreadOut.toString().search(/[...]/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b13
|
||||
title: Copy an Array with the Spread Operator
|
||||
title: Copiar um Array com o Operador Spread
|
||||
challengeType: 1
|
||||
forumTopicId: 301157
|
||||
dashedName: copy-an-array-with-the-spread-operator
|
||||
@ -8,24 +8,24 @@ dashedName: copy-an-array-with-the-spread-operator
|
||||
|
||||
# --description--
|
||||
|
||||
While `slice()` allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new <dfn>spread operator</dfn> allows us to easily copy *all* of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: `...`
|
||||
Enquanto `slice()` nos permite ser seletivo sobre quais elementos de um array copiar, entre várias outras tarefas úteis, o novo operador <dfn>do spread</dfn> da ES6 nos permite facilmente copiar *todos* os elementos de um array, em ordem, com uma sintaxe simples e altamente legível. A sintaxe de spread simplesmente se parece com isso: `...`
|
||||
|
||||
In practice, we can use the spread operator to copy an array like so:
|
||||
Na prática, podemos usar o operador "spread" para copiar um array assim:
|
||||
|
||||
```js
|
||||
let thisArray = [true, true, undefined, false, null];
|
||||
let thatArray = [...thisArray];
|
||||
```
|
||||
|
||||
`thatArray` equals `[true, true, undefined, false, null]`. `thisArray` remains unchanged and `thatArray` contains the same elements as `thisArray`.
|
||||
`thatArray` é igual a `[true, true, undefined, false, null]`. `thisArray` permanece inalterado e `thatArray` contém os mesmos elementos que `thisArray`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `copyMachine` which takes `arr` (an array) and `num` (a number) as arguments. The function is supposed to return a new array made up of `num` copies of `arr`. We have done most of the work for you, but it doesn't work quite right yet. Modify the function using spread syntax so that it works correctly (hint: another method we have already covered might come in handy here!).
|
||||
Definimos uma função, `copyMachine` que recebe `arr` (um array) e `num` (um número) como argumentos. A função deve retornar um novo array composto de `num` cópias de `arr`. Fizemos a maior parte do trabalho para você, mas ainda não funciona muito bem. Modifique a função usando a sintaxe spread para que ela funcione corretamente (dica: outro método já mencionado pode ser útil aqui!).
|
||||
|
||||
# --hints--
|
||||
|
||||
`copyMachine([true, false, true], 2)` should return `[[true, false, true], [true, false, true]]`
|
||||
`copyMachine([true, false, true], 2)` deve retornar `[[true, false, true], [true, false, true]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
@ -34,7 +34,7 @@ assert.deepEqual(copyMachine([true, false, true], 2), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([1, 2, 3], 5)` should return `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
|
||||
`copyMachine([1, 2, 3], 5)` deve retornar `[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
@ -46,13 +46,13 @@ assert.deepEqual(copyMachine([1, 2, 3], 5), [
|
||||
]);
|
||||
```
|
||||
|
||||
`copyMachine([true, true, null], 1)` should return `[[true, true, null]]`
|
||||
`copyMachine([true, true, null], 1)` deve retornar `[[true, true, null]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine([true, true, null], 1), [[true, true, null]]);
|
||||
```
|
||||
|
||||
`copyMachine(["it works"], 3)` should return `[["it works"], ["it works"], ["it works"]]`
|
||||
`copyMachine(["it works"], 3)` deve retornar `[["it works"], ["it works"], ["it works"]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
@ -62,7 +62,7 @@ assert.deepEqual(copyMachine(['it works'], 3), [
|
||||
]);
|
||||
```
|
||||
|
||||
The `copyMachine` function should utilize the `spread operator` with array `arr`
|
||||
A função `copyMachine` deve utilizar o operador `spread` com array `arr`
|
||||
|
||||
```js
|
||||
assert(code.match(/\.\.\.arr/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7a367417b2b2512b12
|
||||
title: Copy Array Items Using slice()
|
||||
title: Copiar Itens de um Array Usando slice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301158
|
||||
dashedName: copy-array-items-using-slice
|
||||
@ -8,7 +8,7 @@ dashedName: copy-array-items-using-slice
|
||||
|
||||
# --description--
|
||||
|
||||
The next method we will cover is `slice()`. Rather than modifying an array, `slice()` copies or *extracts* a given number of elements to a new array, leaving the array it is called upon untouched. `slice()` takes only 2 parameters — the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:
|
||||
O próximo método que abordaremos é `slice()`. Em vez de modificar um array, `slice()` copia ou *extrai* um determinado número de elementos para um novo array, deixando o array em que o método é chamado inalterado. `slice()` recebe apenas 2 parâmetros — o primeiro é o índice aonde começar a extração e o segundo é o índice no qual parar a extração (extração ocorrerá até, mas não incluso, esse índice). Considere isto:
|
||||
|
||||
```js
|
||||
let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
|
||||
@ -16,17 +16,17 @@ let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
|
||||
let todaysWeather = weatherConditions.slice(1, 3);
|
||||
```
|
||||
|
||||
`todaysWeather` would have the value `['snow', 'sleet']`, while `weatherConditions` would still have `['rain', 'snow', 'sleet', 'hail', 'clear']`.
|
||||
`todaysWeather` teria o valor `['snow', 'sleet']`, enquanto `weatherConditions` ainda teria `['rain', 'snow', 'sleet', 'hail', 'clear']`.
|
||||
|
||||
In effect, we have created a new array by extracting elements from an existing array.
|
||||
Assim, criamos um novo array extraindo elementos de um array existente.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `forecast`, that takes an array as an argument. Modify the function using `slice()` to extract information from the argument array and return a new array that contains the string elements `warm` and `sunny`.
|
||||
Definimos uma função, `forecast`, que recebe um array como argumento. Modifique a função usando `slice()` para extrair a informação do array passado como argumento e retorne um novo array contendo os elementos strings `warm` e `sunny`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`forecast` should return `["warm", "sunny"]`
|
||||
`forecast` deve retornar `["warm", "sunny"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -35,7 +35,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
The `forecast` function should utilize the `slice()` method
|
||||
A função `forecast` deve usar o método `slice()`
|
||||
|
||||
```js
|
||||
assert(/\.slice\(/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b16
|
||||
title: Create complex multi-dimensional arrays
|
||||
title: Crie array complexo multidimensional
|
||||
challengeType: 1
|
||||
forumTopicId: 301159
|
||||
dashedName: create-complex-multi-dimensional-arrays
|
||||
@ -8,9 +8,9 @@ dashedName: create-complex-multi-dimensional-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
Awesome! You have just learned a ton about arrays! This has been a fairly high level overview, and there is plenty more to learn about working with arrays, much of which you will see in later sections. But before moving on to looking at <dfn>Objects</dfn>, lets take one more look, and see how arrays can become a bit more complex than what we have seen in previous challenges.
|
||||
Excelente! Você acabou de aprender uma tonelada sobre arrays! Esta foi uma visão geral de nível bastante elevado, e há muito mais para aprender a trabalhar com arrays, muitas das quais você verá em sessões posteriores. Mas antes de passar para a visão de <dfn>objetos</dfn>, vamos dar mais uma olhada e ver como é que as matrizes podem tornar-se um pouco mais complexas do que aquilo que vimos em desafios anteriores.
|
||||
|
||||
One of the most powerful features when thinking of arrays as data structures, is that arrays can contain, or even be completely made up of other arrays. We have seen arrays that contain arrays in previous challenges, but fairly simple ones. However, arrays can contain an infinite depth of arrays that can contain other arrays, each with their own arbitrary levels of depth, and so on. In this way, an array can very quickly become very complex data structure, known as a <dfn>multi-dimensional</dfn>, or nested array. Consider the following example:
|
||||
Uma das características mais poderosas ao pensar em arrays como estruturas de dados, é que arrays podem conter, ou mesmo ser completamente compostas por outros arrays. Vimos arrays que contêm arrays em desafios anteriores, mas que são bastante simples. No entanto, os arrays podem conter uma profundidade infinita de matrizes que podem conter outras matrizes, cada uma com seus próprios níveis arbitrários de profundidade, e assim por diante. Desta forma, um array pode muito rapidamente se tornar uma estrutura de dados muito complexa, conhecida como <dfn>array multi-dimensional</dfn>ou array aninhado. Considere o seguinte exemplo:
|
||||
|
||||
```js
|
||||
let nestedArray = [
|
||||
@ -31,15 +31,15 @@ let nestedArray = [
|
||||
];
|
||||
```
|
||||
|
||||
The `deep` array is nested 2 levels deep. The `deeper` arrays are 3 levels deep. The `deepest` arrays are 4 levels, and the `deepest-est?` is 5.
|
||||
O array `deep` está aninhado com 2 níveis de profundidade. Os arrays `mais profundos` são de 3 níveis de profundidade. Os `arrays` mais profundos são de 4º níveis, e o ainda `mais profundos` é de 5º nível.
|
||||
|
||||
While this example may seem convoluted, this level of complexity is not unheard of, or even unusual, when dealing with large amounts of data. However, we can still very easily access the deepest levels of an array this complex with bracket notation:
|
||||
Embora este exemplo possa parecer complicado, este nível de complexidade não é inédito, ou ainda fora do normal, quando tratando com grandes quantidades de dados. Entretanto, nós ainda podemos facilmente acessar os níveis mais profundos de um array complexo com a notação de colchetes:
|
||||
|
||||
```js
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
```
|
||||
|
||||
This logs the string `deepest-est?`. And now that we know where that piece of data is, we can reset it if we need to:
|
||||
Isso exibe no console a string `deepest-est?`. Agora que sabemos aonde esse pedaço de dado está, nós podemos redefini-lo se precisarmos:
|
||||
|
||||
```js
|
||||
nestedArray[2][1][0][0][0] = 'deeper still';
|
||||
@ -47,15 +47,15 @@ nestedArray[2][1][0][0][0] = 'deeper still';
|
||||
console.log(nestedArray[2][1][0][0][0]);
|
||||
```
|
||||
|
||||
Now it logs `deeper still`.
|
||||
Agora ele mostra no console `deeper still`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a variable, `myNestedArray`, set equal to an array. Modify `myNestedArray`, using any combination of <dfn>strings</dfn>, <dfn>numbers</dfn>, and <dfn>booleans</dfn> for data elements, so that it has exactly five levels of depth (remember, the outer-most array is level 1). Somewhere on the third level, include the string `deep`, on the fourth level, include the string `deeper`, and on the fifth level, include the string `deepest`.
|
||||
Definimos uma variável, `myNestedArray`, definida igual a um array. Modifique `myNestedArray`, usando qualquer combinação de <dfn>strings</dfn>, <dfn>numbers</dfn>, e <dfn>booleans</dfn> para elementos, para que tenha 5 níveis de profundidade (lembre-se, o array mais extremo é de nível 1). Em algum lugar no terceiro nível, inclua a string `deep`, no quarto nível, inclua a string `deeper`, e no quinto nível, inclua a string `deepest`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myNestedArray` should contain only numbers, booleans, and strings as data elements
|
||||
`myNestedArray` deve conter apenas números, booleans e strings como elementos
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -79,7 +79,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` should have exactly 5 levels of depth
|
||||
`myNestedArray` deve ter exatamente 5 níveis de profundidade
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -102,7 +102,7 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` should contain exactly one occurrence of the string `deep` on an array nested 3 levels deep
|
||||
`myNestedArray` deve conter exatamente uma ocorrência da string `deep` no array aninhado de 3 níveis de profundidade
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -131,7 +131,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` should contain exactly one occurrence of the string `deeper` on an array nested 4 levels deep
|
||||
`myNestedArray` deve conter exatamente uma ocorrência da string `deeper` no array aninhado de 4 níveis de profundidade
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -160,7 +160,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myNestedArray` should contain exactly one occurrence of the string `deepest` on an array nested 5 levels deep
|
||||
`myNestedArray` deve conter exatamente uma ocorrência da string `deepest` no array aninhado de 5 níveis de profundidade
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1e
|
||||
title: Generate an Array of All Object Keys with Object.keys()
|
||||
title: Gere um Array de Todas as Chaves de Objeto com Object.keys()
|
||||
challengeType: 1
|
||||
forumTopicId: 301160
|
||||
dashedName: generate-an-array-of-all-object-keys-with-object-keys
|
||||
@ -8,15 +8,15 @@ dashedName: generate-an-array-of-all-object-keys-with-object-keys
|
||||
|
||||
# --description--
|
||||
|
||||
We can also generate an array which contains all the keys stored in an object using the `Object.keys()` method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.
|
||||
Também podemos gerar um array o qual contém todas as chaves armazenadas em um objeto usando o método `Object.keys()` e passando um objeto como argumento. Isso retornará um array com strings representando cada propriedade do objeto. Novamente, não terá uma ordem específica para as entradas no array.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Finish writing the `getArrayOfUsers` function so that it returns an array containing all the properties in the object it receives as an argument.
|
||||
Termine de escrever a função `getArrayOfUsers` para que retorne um array contendo todas as propriedades do objeto que receber como argumento.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `users` object should only contain the keys `Alan`, `Jeff`, `Sarah`, and `Ryan`
|
||||
O objeto `users` deve conter apenas as chaves `Alan`, `Jeff`, `Sarah` e `Ryan`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -28,7 +28,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `getArrayOfUsers` function should return an array which contains all the keys in the `users` object
|
||||
A função `getArrayOfUsers` deve retornar um array o qual contém todas as chaves no objeto `users`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7b367417b2b2512b15
|
||||
title: Iterate Through All an Array's Items Using For Loops
|
||||
title: Itere Através de Todos os Itens de um Array Usando Laços For
|
||||
challengeType: 1
|
||||
forumTopicId: 301161
|
||||
dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
@ -8,9 +8,9 @@ dashedName: iterate-through-all-an-arrays-items-using-for-loops
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes when working with arrays, it is very handy to be able to iterate through each item to find one or more elements that we might need, or to manipulate an array based on which data items meet a certain set of criteria. JavaScript offers several built in methods that each iterate over arrays in slightly different ways to achieve different results (such as `every()`, `forEach()`, `map()`, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple `for` loop.
|
||||
Às vezes quando trabalhando com arrays, é muito útil ser capaz de iterar sobre cada item para encontrar um ou mais elementos que podemos precisar, ou para manipular o array baseado em qual item atende a determinado critério. JavaScript oferece diversos métodos embutidos que fazem iteração sobre arrays de formas ligeiramente diferentes para alcançar resultados diferentes (como `every()`, `forEach()`, `map()`, etc.). Porém, a técnica mais flexível e que oferece-nos a maior capacidade de controle é o simples laço `for`.
|
||||
|
||||
Consider the following:
|
||||
Considere o seguinte:
|
||||
|
||||
```js
|
||||
function greaterThanTen(arr) {
|
||||
@ -26,15 +26,15 @@ function greaterThanTen(arr) {
|
||||
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
|
||||
```
|
||||
|
||||
Using a `for` loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than `10`, and returned a new array, `[12, 14, 80]`, containing those items.
|
||||
Usando o laço `for`, essa função itera o array e acessa cada elemento do array, e submete-o a um teste simples que nós criamos. Dessa forma, nós determinamos de forma fácil e programática qual item é maior que `10`, e retorna um novo array, `[12, 14, 80]`, contendo esses itens.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `filteredArray`, which takes `arr`, a nested array, and `elem` as arguments, and returns a new array. `elem` represents an element that may or may not be present on one or more of the arrays nested within `arr`. Modify the function, using a `for` loop, to return a filtered version of the passed array such that any array nested within `arr` containing `elem` has been removed.
|
||||
Definimos uma função, `filteredArray`, a qual recebe `arr`, um array aninhado, e `elem` como argumentos, e retornar um novo array. `elem` representa um elemento que pode ou não estar presente em um ou mais dos arrays aninhados dentro de `arr`. Modifique a função, usando o laço `for`, para retornar uma versão filtrada do array recebido tal qual que qualquer array aninhado dentro de `arr` contendo `elem` seja removido.
|
||||
|
||||
# --hints--
|
||||
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` should return `[[10, 8, 3], [14, 6, 23]]`
|
||||
`filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)` deve retornar `[[10, 8, 3], [14, 6, 23]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -53,7 +53,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` should return `[["flutes", 4]]`
|
||||
`filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)` deve retornar `[["flutes", 4]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -69,7 +69,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` should return `[["amy", "beth", "sam"]]`
|
||||
`filteredArray([["amy", "beth", "sam"], ["dave", "sean", "peter"]], "peter")` deve retornar `[["amy", "beth", "sam"]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -84,7 +84,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` should return `[]`
|
||||
`filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)` deve retornar `[]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -101,7 +101,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
The `filteredArray` function should utilize a `for` loop
|
||||
A função `filteredArray` deve usar o laço `for`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1d
|
||||
title: Iterate Through the Keys of an Object with a for...in Statement
|
||||
title: Itere Através das Chaves de um Objeto com a declaração for...in
|
||||
challengeType: 1
|
||||
forumTopicId: 301162
|
||||
dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
@ -8,7 +8,7 @@ dashedName: iterate-through-the-keys-of-an-object-with-a-for---in-statement
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a <dfn>for...in</dfn> statement. For our `users` object, this could look like:
|
||||
Às vezes você pode precisar iterar através de todas as chaves dentro de um objeto. Isso requer uma sintaxe específica no JavaScript chamada de declaração <dfn>for...in</dfn>. Para nosso objeto `users`, isso pode se parecer como:
|
||||
|
||||
```js
|
||||
for (let user in users) {
|
||||
@ -16,15 +16,15 @@ for (let user in users) {
|
||||
}
|
||||
```
|
||||
|
||||
This would log `Alan`, `Jeff`, `Sarah`, and `Ryan` - each value on its own line.
|
||||
Isso iria exibir no console `Alan`, `Jeff`, `Sarah` e `Ryan` - cada valor em sua própria linha.
|
||||
|
||||
In this statement, we defined a variable `user`, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.
|
||||
Nessa declaração, definimos uma variável `user` e, como você pode ver, essa variável é redefinida durante cada iteração para cada chave do objeto conforme o comando se repete através do objeto, resultando em cada nome de usuário sendo exibido no console.
|
||||
|
||||
**NOTE:** Objects do not maintain an ordering to stored keys like arrays do; thus a key's position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.
|
||||
**Note:** Objetos não mantém uma ordem para as chaves armazenadas como arrays fazem; Portanto a posição de uma chave em um objeto, ou a ordem relativa na qual ela aparece, é irrelevante quando referenciando ou acessando aquela chave.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We've defined a function `countOnline` which accepts one argument (a users object). Use a <dfn>for...in</dfn> statement within this function to loop through the users object passed into the function and return the number of users whose `online` property is set to `true`. An example of a users object which could be passed to `countOnline` is shown below. Each user will have an `online` property with either a `true` or `false` value.
|
||||
Nós definimos uma função `countOnline` a qual aceita um argumento (um objeto usuário). Use a declaração <dfn>for...in</dfn> dentro dessa função para iterar o objeto users passado para a função, e retorne o número de users o qual possuam a propriedade `online` definida como `true`. Um exemplo de um objeto users o qual pode ser passado para `countOnline` é mostrado abaixo. Cada usuário terá a propriedade `online` com um valor `true` ou `false`.
|
||||
|
||||
```js
|
||||
{
|
||||
@ -42,7 +42,7 @@ We've defined a function `countOnline` which accepts one argument (a users objec
|
||||
|
||||
# --hints--
|
||||
|
||||
The function `countOnline` should use a `for in` statement to iterate through the object keys of the object passed to it.
|
||||
A função `countOnline` deve usar a instrução `for in` para iterar através das chaves de um objeto passado para ele.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -52,19 +52,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The function `countOnline` should return `1` when the object `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` is passed to it
|
||||
A função `countOnline` deve retornar `1` quando o objeto `{ Alan: { online: false }, Jeff: { online: true }, Sarah: { online: false } }` for passado para ele
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj1) === 1);
|
||||
```
|
||||
|
||||
The function `countOnline` should return `2` when the object `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` is passed to it
|
||||
A função `countOnline` deve retornar `2` quando o objeto `{ Alan: { online: true }, Jeff: { online: false }, Sarah: { online: true } }` for passado para ele
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj2) === 2);
|
||||
```
|
||||
|
||||
The function `countOnline` should return `0` when the object `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` is passed to it
|
||||
A função `countOnline` deve retornar `0` quando o objeto `{ Alan: { online: false }, Jeff: { online: false }, Sarah: { online: false } }` for passado para ele
|
||||
|
||||
```js
|
||||
assert(countOnline(usersObj3) === 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7d367417b2b2512b1f
|
||||
title: Modify an Array Stored in an Object
|
||||
title: Modifique o Array Armazenado em um Objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301163
|
||||
dashedName: modify-an-array-stored-in-an-object
|
||||
@ -8,21 +8,21 @@ dashedName: modify-an-array-stored-in-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
Now you've seen all the basic operations for JavaScript objects. You can add, modify, and remove key-value pairs, check if keys exist, and iterate over all the keys in an object. As you continue learning JavaScript you will see even more versatile applications of objects. Additionally, the Data Structures lessons located in the Coding Interview Prep section of the curriculum also cover the ES6 <dfn>Map</dfn> and <dfn>Set</dfn> objects, both of which are similar to ordinary objects but provide some additional features. Now that you've learned the basics of arrays and objects, you're fully prepared to begin tackling more complex problems using JavaScript!
|
||||
Agora você já viu todas as operações básicas para os objetos JavaScript. Você pode adicionar, modificar e remover pares de chave-valor, verifique se a chave existe e itere sobre todas as chaves em um objeto. Conforme continuar aprendendo JavaScript você verá aplicações de objetos ainda mais versáteis. Adicionalmente, as aulas de Estrutura de Dados localizadas na seção Preparação para Entrevista de Codificação do curriculum também cobrem os objetos ES6 <dfn>Map</dfn> e <dfn>Set</dfn>, ambos são semelhantes a objetos comuns, mas fornecem alguns recursos adicionais. Agora que você aprendeu o básico de arrays e objetos, você está totalmente preparado para começar a resolver problemas mais complexos usando JavaScript!
|
||||
|
||||
# --instructions--
|
||||
|
||||
Take a look at the object we've provided in the code editor. The `user` object contains three keys. The `data` key contains five keys, one of which contains an array of `friends`. From this, you can see how flexible objects are as data structures. We've started writing a function `addFriend`. Finish writing it so that it takes a `user` object and adds the name of the `friend` argument to the array stored in `user.data.friends` and returns that array.
|
||||
Dê uma olhada no objeto que fornecemos no editor de código. O objeto `user` contém três chaves. A chave `data` contém 5 chaves, uma delas possui um array de `friends`. A partir disso, você pode ver como objetos são flexíveis assim como estruturas de dados. Nós começamos escrevendo a função `addFriend`. Termine de escrevê-la para que receba um objeto `user` e adicione o nome do argumento `friend` no array armazenado em `user.data.friends` e retorne esse array.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `user` object should have `name`, `age`, and `data` keys.
|
||||
O objeto `user` deve ter as chaves `name`, `age` e `data`.
|
||||
|
||||
```js
|
||||
assert('name' in user && 'age' in user && 'data' in user);
|
||||
```
|
||||
|
||||
The `addFriend` function should accept a `user` object and a `friend` string as arguments and add the friend to the array of `friends` in the `user` object.
|
||||
A função `addFriend` deve aceitar o objeto `user` e a string `friend` como argumentos e adicionar friend ao array `friends` no objeto `user`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`addFriend(user, "Pete")` should return `["Sam", "Kira", "Tomo", "Pete"]`.
|
||||
`addFriend(user, "Pete")` deve retornar `["Sam", "Kira", "Tomo", "Pete"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b19
|
||||
title: Modify an Object Nested Within an Object
|
||||
title: Modifique um Objeto Aninhado Dentro de um Objeto
|
||||
challengeType: 1
|
||||
forumTopicId: 301164
|
||||
dashedName: modify-an-object-nested-within-an-object
|
||||
@ -8,7 +8,7 @@ dashedName: modify-an-object-nested-within-an-object
|
||||
|
||||
# --description--
|
||||
|
||||
Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects. Consider the following:
|
||||
Agora vamos dar uma olhada em um objeto ligeiramente mais complexo. Propriedades de objeto podem ser aninhadas para uma profundidade arbitrária e os seus valores podem ser de qualquer tipo de dado suportado pelo JavaScript, incluindo arrays e até mesmo objetos. Considere o seguinte:
|
||||
|
||||
```js
|
||||
let nestedObject = {
|
||||
@ -26,7 +26,7 @@ let nestedObject = {
|
||||
};
|
||||
```
|
||||
|
||||
`nestedObject` has three properties: `id` (value is a number), `date` (value is a string), and `data` (value is an object with its nested structure). While structures can quickly become complex, we can still use the same notations to access the information we need. To assign the value `10` to the `busy` property of the nested `onlineStatus` object, we use dot notation to reference the property:
|
||||
`nestedObject` possui três propriedades: `id` (o valor é um número), `date` (o valor é uma string) e `data`(o valor é um objeto com sua estrutura aninhada). Enquanto estruturas podem se tornar rapidamente complexas, nós ainda podemos usar as mesmas notações para acessar as informações que precisamos. Para atribuir o valor `10` para a propriedade `busy` do objeto aninhado `onlineStatus`, nós usamos a notação de ponto para referenciar a propriedade:
|
||||
|
||||
```js
|
||||
nestedObject.data.onlineStatus.busy = 10;
|
||||
@ -34,11 +34,11 @@ nestedObject.data.onlineStatus.busy = 10;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Here we've defined an object `userActivity`, which includes another object nested within it. Set the value of the `online` key to `45`.
|
||||
Aqui nós definimos um objeto `userActivity`, o qual inclui outro objeto aninhado dentro dele. Defina o valor da chave `online` para `45`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`userActivity` should have `id`, `date` and `data` properties.
|
||||
`userActivity` deve ter as propriedades `id`, `date` e `data`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -46,19 +46,19 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`userActivity` should have a `data` key set to an object with keys `totalUsers` and `online`.
|
||||
`userActivity` deve ter uma chave `data` definida para um objeto com as chaves `totalUsers` e `online`.
|
||||
|
||||
```js
|
||||
assert('totalUsers' in userActivity.data && 'online' in userActivity.data);
|
||||
```
|
||||
|
||||
The `online` property nested in the `data` key of `userActivity` should be set to `45`
|
||||
A propriedade `online` aninhada na chave `data` de `userActivity` deve ser definida para `45`
|
||||
|
||||
```js
|
||||
assert(userActivity.data.online === 45);
|
||||
```
|
||||
|
||||
The `online` property should be set using dot or bracket notation.
|
||||
A propriedade `online` deve ser definindo usando a notação de ponto ou de colchetes.
|
||||
|
||||
```js
|
||||
assert.strictEqual(code.search(/online: 45/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b0f
|
||||
title: Remove Items from an Array with pop() and shift()
|
||||
title: Remova Itens de um Array com pop() e shift()
|
||||
challengeType: 1
|
||||
forumTopicId: 301165
|
||||
dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
@ -8,9 +8,9 @@ dashedName: remove-items-from-an-array-with-pop-and-shift
|
||||
|
||||
# --description--
|
||||
|
||||
Both `push()` and `unshift()` have corresponding methods that are nearly functional opposites: `pop()` and `shift()`. As you may have guessed by now, instead of adding, `pop()` *removes* an element from the end of an array, while `shift()` removes an element from the beginning. The key difference between `pop()` and `shift()` and their cousins `push()` and `unshift()`, is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.
|
||||
Tanto `push()` e `unshift()` possuem métodos correspondentes que são quase opostos funcionais: `pop()` e `shift()`. Como você já pode ter adivinhado, em vez de adicionar, `pop()` *remove* um elemento do fim de um array, enquanto `shift()` remove um elemento do início. A diferença chave entre `pop()` e `shift()` e seus primos `push()` e `unshift()`, é que nenhum dos métodos recebe parâmetros, e cada um só permite que seja modificado um elemento de cada vez de um array.
|
||||
|
||||
Let's take a look:
|
||||
Vamos dar uma olhada:
|
||||
|
||||
```js
|
||||
let greetings = ['whats up?', 'hello', 'see ya!'];
|
||||
@ -18,29 +18,29 @@ let greetings = ['whats up?', 'hello', 'see ya!'];
|
||||
greetings.pop();
|
||||
```
|
||||
|
||||
`greetings` would have the value `['whats up?', 'hello']`.
|
||||
`greetings` teria o valor `['whats up?', 'hello']`.
|
||||
|
||||
```js
|
||||
greetings.shift();
|
||||
```
|
||||
|
||||
`greetings` would have the value `['hello']`.
|
||||
`greetings` teria o valor `['hello']`.
|
||||
|
||||
We can also return the value of the removed element with either method like this:
|
||||
Nós também podemos retornar o valor do elemento removido com qualquer método dessa forma:
|
||||
|
||||
```js
|
||||
let popped = greetings.pop();
|
||||
```
|
||||
|
||||
`greetings` would have the value `[]`, and `popped` would have the value `hello`.
|
||||
`greetings` teria o valor `[]` e `popped` teria o valor `hello`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a function, `popShift`, which takes an array as an argument and returns a new array. Modify the function, using `pop()` and `shift()`, to remove the first and last elements of the argument array, and assign the removed elements to their corresponding variables, so that the returned array contains their values.
|
||||
Nós definimos uma função, `popShift`, a qual recebe um array como argumento e retorna um novo array. Modifique a função, usando `pop()` e `shift()`, para remover o primeiro e o último elemento do array passado como argumento, e atribua os valores removidos para suas variáveis correspondentes, para que o array retornado contenha seus valores.
|
||||
|
||||
# --hints--
|
||||
|
||||
`popShift(["challenge", "is", "not", "complete"])` should return `["challenge", "complete"]`
|
||||
`popShift(["challenge", "is", "not", "complete"])` deve retornar `["challenge", "complete"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
@ -49,13 +49,13 @@ assert.deepEqual(popShift(['challenge', 'is', 'not', 'complete']), [
|
||||
]);
|
||||
```
|
||||
|
||||
The `popShift` function should utilize the `pop()` method
|
||||
A função `popShift` deve utilizar o método `pop()`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.pop\(/), -1);
|
||||
```
|
||||
|
||||
The `popShift` function should utilize the `shift()` method
|
||||
A função `popShift` deve utilizar o método `shift()`
|
||||
|
||||
```js
|
||||
assert.notStrictEqual(popShift.toString().search(/\.shift\(/), -1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d78b2367417b2b2512b10
|
||||
title: Remove Items Using splice()
|
||||
title: Remova Itens Usando splice()
|
||||
challengeType: 1
|
||||
forumTopicId: 301166
|
||||
dashedName: remove-items-using-splice
|
||||
@ -8,9 +8,9 @@ dashedName: remove-items-using-splice
|
||||
|
||||
# --description--
|
||||
|
||||
Ok, so we've learned how to remove elements from the beginning and end of arrays using `shift()` and `pop()`, but what if we want to remove an element from somewhere in the middle? Or remove more than one element at once? Well, that's where `splice()` comes in. `splice()` allows us to do just that: **remove any number of consecutive elements** from anywhere in an array.
|
||||
Ok, então aprendemos como remover elementos do início e do fim de arrays usando `shift()` e `pop()`, mas e se quisermos remover um elemento de algum lugar do meio? Ou remover mais de um elemento de uma vez? Bem, é aí que `splice()` pode ser útil. `splice()` nos permite fazer isso: **remova qualquer número de elementos consecutivos** de qualquer lugar no array.
|
||||
|
||||
`splice()` can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of `splice()` are integers which represent indexes, or positions, of the array that `splice()` is being called upon. And remember, arrays are *zero-indexed*, so to indicate the first element of an array, we would use `0`. `splice()`'s first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:
|
||||
`splice` pode receber 3 parâmetros, mas por agora, nós focaremos apenas nos 2 primeiros. Os dois primeiros parâmetros de `splice()` são inteiros que representam índices, ou posições, do array do qual o método `splice()` está sendo chamado. E lembre-se, arrays são *indexados a zero*, então para indicar o primeiro elemento do array, usaríamos `0`. O primeiro parâmetro de `splice()` representa o índice no array do qual começar a remover elementos, enquanto o segundo parâmetro indica o número de elementos a serem removidos. Por exemplo:
|
||||
|
||||
```js
|
||||
let array = ['today', 'was', 'not', 'so', 'great'];
|
||||
@ -18,9 +18,9 @@ let array = ['today', 'was', 'not', 'so', 'great'];
|
||||
array.splice(2, 2);
|
||||
```
|
||||
|
||||
Here we remove 2 elements, beginning with the third element (at index 2). `array` would have the value `['today', 'was', 'great']`.
|
||||
Aqui nós removemos 2 elementos, começando com o terceiro elemento (no índice 2). `array` teria o valor `['today', 'was', 'great']`.
|
||||
|
||||
`splice()` not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:
|
||||
`splice()` não apenas modifica o array do qual está sendo chamado, mas também retorna um novo array contendo os valores dos elementos removidos:
|
||||
|
||||
```js
|
||||
let array = ['I', 'am', 'feeling', 'really', 'happy'];
|
||||
@ -28,15 +28,15 @@ let array = ['I', 'am', 'feeling', 'really', 'happy'];
|
||||
let newArray = array.splice(3, 2);
|
||||
```
|
||||
|
||||
`newArray` has the value `['really', 'happy']`.
|
||||
`newArray` tem o valor `['really', 'happy']`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We've initialized an array `arr`. Use `splice()` to remove elements from `arr`, so that it only contains elements that sum to the value of `10`.
|
||||
Iniciamos um array `arr`. Use `splice()` para remover elementos do `arr`, para que apenas contenha elementos que somam ao valor de `10`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change the original line of `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
|
||||
Você não deve alterar a linha original: `const arr = [2, 4, 5, 1, 7, 5, 2, 1];`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -44,7 +44,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`arr` should only contain elements that sum to `10`.
|
||||
`arr` deve conter apenas elementos que somam a `10`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(
|
||||
@ -53,13 +53,13 @@ assert.strictEqual(
|
||||
);
|
||||
```
|
||||
|
||||
Your code should utilize the `splice()` method on `arr`.
|
||||
Seu código deve utilizar o método `splice()` em `arr`.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/arr\.splice\(/));
|
||||
```
|
||||
|
||||
The splice should only remove elements from `arr` and not add any additional elements to `arr`.
|
||||
O splice deve remover apenas os elementos de `arr` e não adicionar qualquer elemento adicional para `arr`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7e367417b2b2512b20
|
||||
title: Use an Array to Store a Collection of Data
|
||||
title: Use um Array para Armazenar uma Coleção de Dados
|
||||
challengeType: 1
|
||||
forumTopicId: 301167
|
||||
dashedName: use-an-array-to-store-a-collection-of-data
|
||||
@ -8,16 +8,16 @@ dashedName: use-an-array-to-store-a-collection-of-data
|
||||
|
||||
# --description--
|
||||
|
||||
The below is an example of the simplest implementation of an array data structure. This is known as a <dfn>one-dimensional array</dfn>, meaning it only has one level, or that it does not have any other arrays nested within it. Notice it contains <dfn>booleans</dfn>, <dfn>strings</dfn>, and <dfn>numbers</dfn>, among other valid JavaScript data types:
|
||||
Abaixo está um exemplo da implementação mais simples de uma estrutura de dados array. Isso é conhecido como <dfn>array unidimensional</dfn>, significando que tem apenas 1 nível de profundidade, ou que não possui nenhum outro array aninhado dentro de si. Note que possui <dfn>booleans</dfn>, <dfn>strings</dfn> e <dfn>numbers</dfn>, entre outros tipos de dados do JavaScript válidos:
|
||||
|
||||
```js
|
||||
let simpleArray = ['one', 2, 'three', true, false, undefined, null];
|
||||
console.log(simpleArray.length);
|
||||
```
|
||||
|
||||
The `console.log` call displays `7`.
|
||||
A chamada a `console.log` exibe `7`.
|
||||
|
||||
All arrays have a length property, which as shown above, can be very easily accessed with the syntax `Array.length`. A more complex implementation of an array can be seen below. This is known as a <dfn>multi-dimensional array</dfn>, or an array that contains other arrays. Notice that this array also contains JavaScript <dfn>objects</dfn>, which we will examine very closely in our next section, but for now, all you need to know is that arrays are also capable of storing complex objects.
|
||||
Todos os arrays possuem uma propriedade length, conforme mostrada acima, pode ser muito facilmente acessado com a sintaxe `Array.length`. Uma implementação mais complexa de um array pode ser vista abaixo. Isso é conhecido como um <dfn>array multidimensional</dfn>, ou um array que contém outros arrays. Note que esse array também contém <dfn>objetos</dfn> JavaScript, os quais examinaremos bem de perto na próxima seção, mas por agora, tudo que você precisa saber é que arrays também são capazes de armazenar objetos complexos.
|
||||
|
||||
```js
|
||||
let complexArray = [
|
||||
@ -46,35 +46,35 @@ let complexArray = [
|
||||
|
||||
# --instructions--
|
||||
|
||||
We have defined a variable called `yourArray`. Complete the statement by assigning an array of at least 5 elements in length to the `yourArray` variable. Your array should contain at least one <dfn>string</dfn>, one <dfn>number</dfn>, and one <dfn>boolean</dfn>.
|
||||
Definimos uma variável chamada `yourArray`. Complete a instrução atribuindo um array de pelo menos 5 elementos de comprimento à variável para a variável `yourArray`. Seu array deve conter pelo menos um <dfn>string</dfn>, um <dfn>number</dfn> e um <dfn>boolean</dfn>.
|
||||
|
||||
# --hints--
|
||||
|
||||
`yourArray` should be an array.
|
||||
`yourArray` deve ser um array.
|
||||
|
||||
```js
|
||||
assert.strictEqual(Array.isArray(yourArray), true);
|
||||
```
|
||||
|
||||
`yourArray` should be at least 5 elements long.
|
||||
`yourArray` deve ter pelo menos 5 elementos.
|
||||
|
||||
```js
|
||||
assert.isAtLeast(yourArray.length, 5);
|
||||
```
|
||||
|
||||
`yourArray` should contain at least one `boolean`.
|
||||
`yourArray` deve conter pelo menos um `boolean`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'boolean').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` should contain at least one `number`.
|
||||
`yourArray` deve conter pelo menos um `number`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'number').length >= 1);
|
||||
```
|
||||
|
||||
`yourArray` should contain at least one `string`.
|
||||
`yourArray` deve conter pelo menos um `string`.
|
||||
|
||||
```js
|
||||
assert(yourArray.filter((el) => typeof el === 'string').length >= 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b7c367417b2b2512b1b
|
||||
title: Use the delete Keyword to Remove Object Properties
|
||||
title: Use a Palavra-Chave delete para Remover Propriedades de Objetos
|
||||
challengeType: 1
|
||||
forumTopicId: 301168
|
||||
dashedName: use-the-delete-keyword-to-remove-object-properties
|
||||
@ -8,11 +8,11 @@ dashedName: use-the-delete-keyword-to-remove-object-properties
|
||||
|
||||
# --description--
|
||||
|
||||
Now you know what objects are and their basic features and advantages. In short, they are key-value stores which provide a flexible, intuitive way to structure data, ***and***, they provide very fast lookup time. Throughout the rest of these challenges, we will describe several common operations you can perform on objects so you can become comfortable applying these useful data structures in your programs.
|
||||
Agora você sabe o que objetos são, seus recursos básicos e suas vantagens. Resumindo, ele são uma forma de armazenar chave-valor que provê uma forma flexível e intuitiva de estruturar dados, ***e***, eles fornecem um desempenho rápido para acessá-los. Ao longo do resto destes desafios, descreveremos diversas operações que você pode executar em objetos, com a finalidade de torná-lo confortável ao usar essas estruturas de dados úteis em seus programas.
|
||||
|
||||
In earlier challenges, we have both added to and modified an object's key-value pairs. Here we will see how we can *remove* a key-value pair from an object.
|
||||
Nos desafios anteriores, nós adicionamos e modificamos os pares de chave-valor de objetos. Aqui veremos como podemos *remover* uma chave-valor de um obeto.
|
||||
|
||||
Let's revisit our `foods` object example one last time. If we wanted to remove the `apples` key, we can remove it by using the `delete` keyword like this:
|
||||
Vamos revisitar nosso objeto de exemplo `foods` uma última vez. Se quisermos remover a chave `apples`, podemos removê-lo usando a palavra-chave `delete` assim:
|
||||
|
||||
```js
|
||||
delete foods.apples;
|
||||
@ -20,11 +20,11 @@ delete foods.apples;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the delete keyword to remove the `oranges`, `plums`, and `strawberries` keys from the `foods` object.
|
||||
Use a palavra-chave delete para remover as chaves `oranges`, `plums` e `strawberries` do objeto `foods`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `foods` object should only have three keys: `apples`, `grapes`, and `bananas`.
|
||||
O objeto `foods` deve ter apenas três chaves: `apples`, `grapes` e `bananas`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `oranges`, `plums`, and `strawberries` keys should be removed using `delete`.
|
||||
As chaves `oranges`, `plums` e `strawberries` devem ser removidos usando `delete`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392ca
|
||||
title: Access Array Data with Indexes
|
||||
title: Acessar Array de dados com índices
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZQbTz'
|
||||
forumTopicId: 16158
|
||||
@ -9,13 +9,13 @@ dashedName: access-array-data-with-indexes
|
||||
|
||||
# --description--
|
||||
|
||||
We can access the data inside arrays using <dfn>indexes</dfn>.
|
||||
Podemos acessar os dados dentro de arrays usando <dfn>indexes</dfn>.
|
||||
|
||||
Array indexes are written in the same bracket notation that strings use, except that instead of specifying a character, they are specifying an entry in the array. Like strings, arrays use <dfn>zero-based</dfn> indexing, so the first element in an array has an index of `0`.
|
||||
Os índices de um array são escritos na mesma notação com colchetes que as strings usam, exceto que em vez de especificar um caractere, eles estão especificando um item do array. Assim como com strings, arrays usam indexação <dfn>zero-based</dfn>, de forma que o primeiro elemento de um array possui índice `0`.
|
||||
|
||||
<br>
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
var array = [50,60,70];
|
||||
@ -23,17 +23,17 @@ array[0];
|
||||
var data = array[1];
|
||||
```
|
||||
|
||||
`array[0]` is now `50`, and `data` has the value `60`.
|
||||
`array[0]` agora é `50` e `data` tem o valor `60`.
|
||||
|
||||
**Note:** There shouldn't be any spaces between the array name and the square brackets, like `array [0]`. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
|
||||
**Nota:** Não deve haver nenhum espaço entre o nome do array e os colchetes, como `array [0]`. Embora JavaScript seja capaz de processar isso corretamente, isso pode confundir outros programadores lendo seu código.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a variable called `myData` and set it to equal the first value of `myArray` using bracket notation.
|
||||
Crie uma variável chamada `myData` e defina-a como igual ao primeiro valor de `myArray` usando notação de colchetes.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `myData` should equal the first value of `myArray`.
|
||||
A variável `myData` deve ser igual ao primeiro valor de `myArray`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -51,7 +51,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The data in variable `myArray` should be accessed using bracket notation.
|
||||
O dado na variável `myArray` deve ser acessado usando notação de colchetes.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56592a60ddddeae28f7aa8e1
|
||||
title: Access Multi-Dimensional Arrays With Indexes
|
||||
title: Acessar Arrays Multidimensionais com Índices
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ckND4Cq'
|
||||
forumTopicId: 16159
|
||||
@ -9,9 +9,9 @@ dashedName: access-multi-dimensional-arrays-with-indexes
|
||||
|
||||
# --description--
|
||||
|
||||
One way to think of a <dfn>multi-dimensional</dfn> array, is as an *array of arrays*. When you use brackets to access your array, the first set of brackets refers to the entries in the outer-most (the first level) array, and each additional pair of brackets refers to the next level of entries inside.
|
||||
Uma maneira de pensar em um array <dfn>multi-dimensional</dfn> é como um *array de arrays*. Quando você usa colchetes para acessar seu array, o primeiro conjunto de colchetes se refere às entradas no array mais exterior (o primeiro nível), e cada par adicional de colchetes refere-se ao próximo nível de entradas interno.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
var arr = [
|
||||
@ -25,23 +25,23 @@ arr[3][0];
|
||||
arr[3][0][1];
|
||||
```
|
||||
|
||||
`arr[3]` is `[[10, 11, 12], 13, 14]`, `arr[3][0]` is `[10, 11, 12]`, and `arr[3][0][1]` is `11`.
|
||||
`arr[3]` é `[[10, 11, 12], 13, 14]`, `arr[3][0]` é `[10, 11, 12]`, e `arr[3][0][1]` é `11`.
|
||||
|
||||
**Note:** There shouldn't be any spaces between the array name and the square brackets, like `array [0][0]` and even this `array [0] [0]` is not allowed. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
|
||||
**Nota:** Não deve haver nenhum espaço entre o nome do array e os colchetes como `array [0][0]` e até mesmo `array [0] [0]` não é permitido. Embora JavaScript seja capaz de processar isso corretamente, isso pode confundir outros programadores lendo seu código.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using bracket notation select an element from `myArray` such that `myData` is equal to `8`.
|
||||
Utilizando notação de colchetes selecione um elemento de `myArray` de forma que `myData` seja igual a `8`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myData` should be equal to `8`.
|
||||
`myData` deve ser igual a `8`.
|
||||
|
||||
```js
|
||||
assert(myData === 8);
|
||||
```
|
||||
|
||||
You should be using bracket notation to read the correct value from `myArray`.
|
||||
Você deve usar notação de colchetes para ler o valor correto de `myArray`.
|
||||
|
||||
```js
|
||||
assert(/myData=myArray\[2\]\[1\]/.test(__helpers.removeWhiteSpace(code)));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cd
|
||||
title: Accessing Nested Arrays
|
||||
title: Acessando Arrays Aninhados
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
|
||||
forumTopicId: 16160
|
||||
@ -9,9 +9,9 @@ dashedName: accessing-nested-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, array bracket notation can be chained to access nested arrays.
|
||||
Como vimos em exemplos anteriores, objetos podem conter tanto objetos aninhados quanto arrays aninhados. Semelhante ao acesso de objetos aninhados, a notação de colchetes pode ser encadeada para se acessar arrays aninhados.
|
||||
|
||||
Here is an example of how to access a nested array:
|
||||
Aqui está um exemplo de como se acessar um array aninhado:
|
||||
|
||||
```js
|
||||
var ourPets = [
|
||||
@ -36,21 +36,21 @@ ourPets[0].names[1];
|
||||
ourPets[1].names[0];
|
||||
```
|
||||
|
||||
`ourPets[0].names[1]` would be the string `Fluffy`, and `ourPets[1].names[0]` would be the string `Spot`.
|
||||
`ourPets[0].names[1]` seria a string `Fluffy` e `ourPets[1].names[0]` seria a string `Spot`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using dot and bracket notation, set the variable `secondTree` to the second item in the `trees` list from the `myPlants` object.
|
||||
Usando a notação de ponto e de colchetes, defina a variável `secondTree` para o segundo item na lista de `trees` do objeto `myPlants`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`secondTree` should equal the string `pine`.
|
||||
`secondTree` deve ser igual à string `pine`.
|
||||
|
||||
```js
|
||||
assert(secondTree === 'pine');
|
||||
```
|
||||
|
||||
Your code should use dot and bracket notation to access `myPlants`.
|
||||
Seu código deve usar notação de ponto e colchetes para acessar `myPlants`.
|
||||
|
||||
```js
|
||||
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244cc
|
||||
title: Accessing Nested Objects
|
||||
title: Acessando Objetos Aninhados
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRnRnfa'
|
||||
forumTopicId: 16161
|
||||
@ -9,9 +9,9 @@ dashedName: accessing-nested-objects
|
||||
|
||||
# --description--
|
||||
|
||||
The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
|
||||
As sub propriedades de objetos podem ser acessadas ao encadear a notação de ponto e de colchetes.
|
||||
|
||||
Here is a nested object:
|
||||
Aqui está um objeto aninhado:
|
||||
|
||||
```js
|
||||
var ourStorage = {
|
||||
@ -30,21 +30,21 @@ ourStorage.cabinet["top drawer"].folder2;
|
||||
ourStorage.desk.drawer;
|
||||
```
|
||||
|
||||
`ourStorage.cabinet["top drawer"].folder2` would be the string `secrets`, and `ourStorage.desk.drawer` would be the string `stapler`.
|
||||
`ourStorage.cabinet["top drawer"].folder2` seria a string `secrets` e `ourStorage.desk.drawer` seria a string `stapler`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Access the `myStorage` object and assign the contents of the `glove box` property to the `gloveBoxContents` variable. Use dot notation for all properties where possible, otherwise use bracket notation.
|
||||
Acesse o objeto `myStorage` e atribua o conteúdo da propriedade `glove box` para a variável `gloveBoxContents`. Use notação de ponto para todas as propriedades sempre que possível, caso contrário, use a notação de colchetes.
|
||||
|
||||
# --hints--
|
||||
|
||||
`gloveBoxContents` should equal the string `maps`.
|
||||
`gloveBoxContents` deveria ser igual à string `maps`.
|
||||
|
||||
```js
|
||||
assert(gloveBoxContents === 'maps');
|
||||
```
|
||||
|
||||
Your code should use dot and bracket notation to access `myStorage`.
|
||||
Seu código deve usar notação de ponto e de colchetes para acessar `myStorage`.
|
||||
|
||||
```js
|
||||
assert(/=\s*myStorage\.car\.inside\[\s*("|')glove box\1\s*\]/g.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c8
|
||||
title: Accessing Object Properties with Bracket Notation
|
||||
title: Acessando Propriedades de Objeto com Notação de Colchetes
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBvmEHP'
|
||||
forumTopicId: 16163
|
||||
@ -9,11 +9,11 @@ dashedName: accessing-object-properties-with-bracket-notation
|
||||
|
||||
# --description--
|
||||
|
||||
The second way to access the properties of an object is bracket notation (`[]`). If the property of the object you are trying to access has a space in its name, you will need to use bracket notation.
|
||||
A segunda forma para acessar as propriedades de um objeto é a notação de colchetes (`[]`). Se a propriedade do objeto que você está tentando acessar possui um espaço no seu nome, você irá precisar usar a notação de colchetes.
|
||||
|
||||
However, you can still use bracket notation on object properties without spaces.
|
||||
No entanto, você ainda pode usar a notação de colchetes nas propriedades dos objetos sem espaços.
|
||||
|
||||
Here is a sample of using bracket notation to read an object's property:
|
||||
Aqui está um exemplo usando a notação de colchetes para ler uma propriedade de um objeto:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
@ -26,41 +26,41 @@ myObj['More Space'];
|
||||
myObj["NoSpace"];
|
||||
```
|
||||
|
||||
`myObj["Space Name"]` would be the string `Kirk`, `myObj['More Space']` would be the string `Spock`, and `myObj["NoSpace"]` would be the string `USS Enterprise`.
|
||||
`myObj["Space Name"]` seria a string `Kirk`, `myObj['More Space']` seria a string `Spock` e `myObj["NoSpace"]` seria a string `USS Enterprise`.
|
||||
|
||||
Note that property names with spaces in them must be in quotes (single or double).
|
||||
Note que os nomes das propriedades com espaços neles precisam estar entre aspas (simples ou duplas).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Read the values of the properties `an entree` and `the drink` of `testObj` using bracket notation and assign them to `entreeValue` and `drinkValue` respectively.
|
||||
Leia os valores das propriedades `an entree` e `the drink` de `testObj` usando notação de colchetes e atribua-os a `entreeValue` e `drinkValue` respectivamente.
|
||||
|
||||
# --hints--
|
||||
|
||||
`entreeValue` should be a string
|
||||
`entreeValue` devem ser uma string
|
||||
|
||||
```js
|
||||
assert(typeof entreeValue === 'string');
|
||||
```
|
||||
|
||||
The value of `entreeValue` should be the string `hamburger`
|
||||
O valor de `entreeValue` deve ser a string `hamburger`
|
||||
|
||||
```js
|
||||
assert(entreeValue === 'hamburger');
|
||||
```
|
||||
|
||||
`drinkValue` should be a string
|
||||
`drinkValue` deve ser uma string
|
||||
|
||||
```js
|
||||
assert(typeof drinkValue === 'string');
|
||||
```
|
||||
|
||||
The value of `drinkValue` should be the string `water`
|
||||
O valor de `drinkValue` deve ser a string `water`
|
||||
|
||||
```js
|
||||
assert(drinkValue === 'water');
|
||||
```
|
||||
|
||||
You should use bracket notation twice
|
||||
Você deve usar a notação de colchetes duas vezes
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\s*?\[('|")[^'"]+\1\]/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c7
|
||||
title: Accessing Object Properties with Dot Notation
|
||||
title: Acessando Propriedades de Objetos com Notação de Pontos
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cGryJs8'
|
||||
forumTopicId: 16164
|
||||
@ -9,11 +9,11 @@ dashedName: accessing-object-properties-with-dot-notation
|
||||
|
||||
# --description--
|
||||
|
||||
There are two ways to access the properties of an object: dot notation (`.`) and bracket notation (`[]`), similar to an array.
|
||||
Existem duas formas para acessar as propriedades de um objeto: notação de ponto (`.`) e notação de colchetes (`[]`), de forma similar a um array.
|
||||
|
||||
Dot notation is what you use when you know the name of the property you're trying to access ahead of time.
|
||||
Notação de ponto é o que você utiliza quando você sabe o nome da propriedade que você está tentando acessar antecipadamente.
|
||||
|
||||
Here is a sample of using dot notation (`.`) to read an object's property:
|
||||
Aqui está um exemplo usando notação de ponto (`.`) para ler uma propriedade do objeto:
|
||||
|
||||
```js
|
||||
var myObj = {
|
||||
@ -24,38 +24,38 @@ var prop1val = myObj.prop1;
|
||||
var prop2val = myObj.prop2;
|
||||
```
|
||||
|
||||
`prop1val` would have a value of the string `val1`, and `prop2val` would have a value of the string `val2`.
|
||||
`prop1val` teria o valor `val1`, e `prop2val` teria o valor `val2`.
|
||||
# --instructions--
|
||||
|
||||
Read in the property values of `testObj` using dot notation. Set the variable `hatValue` equal to the object's property `hat` and set the variable `shirtValue` equal to the object's property `shirt`.
|
||||
Leia os valores de propriedade de `testObj` usando a notação de ponto. Defina a variável `hatValue` igual à propriedade `hat` do objeto e defina a variável `shirtValue` igual à propriedade `shirt` do objeto.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hatValue` should be a string
|
||||
`hatValue` deve ser uma string
|
||||
|
||||
```js
|
||||
assert(typeof hatValue === 'string');
|
||||
```
|
||||
|
||||
The value of `hatValue` should be the string `ballcap`
|
||||
O valor de `hatValue` deve ser a string `ballcap`
|
||||
|
||||
```js
|
||||
assert(hatValue === 'ballcap');
|
||||
```
|
||||
|
||||
`shirtValue` should be a string
|
||||
`shirtValue` deve ser a string
|
||||
|
||||
```js
|
||||
assert(typeof shirtValue === 'string');
|
||||
```
|
||||
|
||||
The value of `shirtValue` should be the string `jersey`
|
||||
O valor de `shirtValue` deve ser a string `jersey`
|
||||
|
||||
```js
|
||||
assert(shirtValue === 'jersey');
|
||||
```
|
||||
|
||||
You should use dot notation twice
|
||||
Você deve usar notação de ponto duas vezes
|
||||
|
||||
```js
|
||||
assert(code.match(/testObj\.\w+/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c9
|
||||
title: Accessing Object Properties with Variables
|
||||
title: Acessando Propriedades de Objetos com Variáveis
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cnQyKur'
|
||||
forumTopicId: 16165
|
||||
@ -9,9 +9,9 @@ dashedName: accessing-object-properties-with-variables
|
||||
|
||||
# --description--
|
||||
|
||||
Another use of bracket notation on objects is to access a property which is stored as the value of a variable. This can be very useful for iterating through an object's properties or when accessing a lookup table.
|
||||
Outro uso de notação de colchetes em objetos é para acessar a propriedade a qual está armazenada como o valor de uma variável. Isso pode ser muito útil para iterar através das propriedades de um objeto ou quando acessando uma tabela de pesquisa.
|
||||
|
||||
Here is an example of using a variable to access a property:
|
||||
Aqui está um exemplo de usar uma variável para acessar uma propriedade:
|
||||
|
||||
```js
|
||||
var dogs = {
|
||||
@ -22,9 +22,9 @@ var myBreed = dogs[myDog];
|
||||
console.log(myBreed);
|
||||
```
|
||||
|
||||
The string `Doberman` would be displayed in the console.
|
||||
A string `Doberman` seria exibida no console.
|
||||
|
||||
Another way you can use this concept is when the property's name is collected dynamically during the program execution, as follows:
|
||||
Outra forma de você usar esse conceito é quando o nome da propriedade é coletado dinamicamente, durante a execução do programa, da seguinte forma:
|
||||
|
||||
```js
|
||||
var someObj = {
|
||||
@ -38,47 +38,47 @@ var someProp = propPrefix("Name");
|
||||
console.log(someObj[someProp]);
|
||||
```
|
||||
|
||||
`someProp` would have a value of the string `propName`, and the string `John` would be displayed in the console.
|
||||
`someProp` teria o valor da string `propName` e a string `John` seria exibida no console.
|
||||
|
||||
Note that we do *not* use quotes around the variable name when using it to access the property because we are using the *value* of the variable, not the *name*.
|
||||
Observe que *não* usamos aspas em torno do nome da variável ao usá-la para acessar a propriedade, porque estamos usando o *valor* da variável, e não o *nome*.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set the `playerNumber` variable to `16`. Then, use the variable to look up the player's name and assign it to `player`.
|
||||
Defina a variável `playerNumber` para ser `16`. Então, use a variável para procurar o nome do jogador e atribuí-la a `player`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`playerNumber` should be a number
|
||||
`playerNumber` deve ser um número
|
||||
|
||||
```js
|
||||
assert(typeof playerNumber === 'number');
|
||||
```
|
||||
|
||||
The variable `player` should be a string
|
||||
A variável `player` deve ser uma string
|
||||
|
||||
```js
|
||||
assert(typeof player === 'string');
|
||||
```
|
||||
|
||||
The value of `player` should be the string `Montana`
|
||||
O valor de `player` deve ser a string `Montana`
|
||||
|
||||
```js
|
||||
assert(player === 'Montana');
|
||||
```
|
||||
|
||||
You should use bracket notation to access `testObj`
|
||||
Você deve usar a notação de colchetes para acessar `testObj`
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[.*?\]/.test(code));
|
||||
```
|
||||
|
||||
You should not assign the value `Montana` to the variable `player` directly.
|
||||
Você não deve usar o valor `Montana` diretamente para a variável `player`.
|
||||
|
||||
```js
|
||||
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
|
||||
```
|
||||
|
||||
You should be using the variable `playerNumber` in your bracket notation
|
||||
Você deve estar usando a variável `playerNumber` na sua notação de colchetes
|
||||
|
||||
```js
|
||||
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d2
|
||||
title: Add New Properties to a JavaScript Object
|
||||
title: Adicione Novas Propriedades para um Objeto JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQe38UD'
|
||||
forumTopicId: 301169
|
||||
@ -9,23 +9,23 @@ dashedName: add-new-properties-to-a-javascript-object
|
||||
|
||||
# --description--
|
||||
|
||||
You can add new properties to existing JavaScript objects the same way you would modify them.
|
||||
Você pode adicionar novas propriedades para um objeto JavaScript existente da mesma forma que você iria modificá-los.
|
||||
|
||||
Here's how we would add a `bark` property to `ourDog`:
|
||||
Aqui está como adicionaríamos uma propriedade `bark` para `ourDog`:
|
||||
|
||||
```js
|
||||
ourDog.bark = "bow-wow";
|
||||
```
|
||||
|
||||
or
|
||||
ou
|
||||
|
||||
```js
|
||||
ourDog["bark"] = "bow-wow";
|
||||
```
|
||||
|
||||
Now when we evaluate `ourDog.bark`, we'll get his bark, `bow-wow`.
|
||||
Agora, quando acessamos `ourDog.bark`, nós teremos o seu latido, `bow-wow`.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
@ -40,17 +40,17 @@ ourDog.bark = "bow-wow";
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a `bark` property to `myDog` and set it to a dog sound, such as "woof". You may use either dot or bracket notation.
|
||||
Adicione a propriedade `bark` para `myDog` e defina-a para um som de um cachorro, como "woof". Você pode usar tanto notação de ponto quando de colchetes.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should add the property `bark` to `myDog`.
|
||||
Você deve adicionar a propriedade `bark` para `myDog`.
|
||||
|
||||
```js
|
||||
assert(myDog.bark !== undefined);
|
||||
```
|
||||
|
||||
You should not add `bark` to the initialization of `myDog`.
|
||||
Você não deve adicionar `bark` na inicialização de `myDog`.
|
||||
|
||||
```js
|
||||
assert(!/bark[^\n]:/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb3bdef
|
||||
title: Add Two Numbers with JavaScript
|
||||
title: Adicione Dois Números com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KBAG'
|
||||
forumTopicId: 16650
|
||||
@ -9,33 +9,33 @@ dashedName: add-two-numbers-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
`Number` is a data type in JavaScript which represents numeric data.
|
||||
`Number` é um tipo de dado em JavaScript o qual representa um dado numérico.
|
||||
|
||||
Now let's try to add two numbers using JavaScript.
|
||||
Agora vamos tentar adicionar dois números usando JavaScript.
|
||||
|
||||
JavaScript uses the `+` symbol as an addition operator when placed between two numbers.
|
||||
JavaScript utiliza o símbolo `+` como um operador de adição quando colocado entre dois números.
|
||||
|
||||
**Example:**
|
||||
**Exemplo:**
|
||||
|
||||
```js
|
||||
myVar = 5 + 10;
|
||||
```
|
||||
|
||||
`myVar` now has the value `15`.
|
||||
`myVar` agora tem o valor de `15`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0` so that sum will equal `20`.
|
||||
Modifique o `0` para que a soma seja igual a `20`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum` should equal `20`.
|
||||
`soma` deve ser igual a `20`.
|
||||
|
||||
```js
|
||||
assert(sum === 20);
|
||||
```
|
||||
|
||||
You should use the `+` operator.
|
||||
Você deve usar o operador `+`.
|
||||
|
||||
```js
|
||||
assert(/\+/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244de
|
||||
title: Adding a Default Option in Switch Statements
|
||||
title: Adicionando uma Opção Padrão (default) em Instruções Switch
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c3JvVfg'
|
||||
forumTopicId: 16653
|
||||
@ -9,9 +9,9 @@ dashedName: adding-a-default-option-in-switch-statements
|
||||
|
||||
# --description--
|
||||
|
||||
In a `switch` statement you may not be able to specify all possible values as `case` statements. Instead, you can add the `default` statement which will be executed if no matching `case` statements are found. Think of it like the final `else` statement in an `if/else` chain.
|
||||
Na instrução `switch` você não deve ser capaz de especificar todos os possíveis valores como instruções `case`. Ao invés disso, você pode adicionar a instrução `default` a qual será executada se nenhuma instrução `case` correspondente for encontrada. Pense nisso como a instrução final `else` em uma cadeia de `if/else`.
|
||||
|
||||
A `default` statement should be the last case.
|
||||
A instrução `default` deve ser o último caso.
|
||||
|
||||
```js
|
||||
switch (num) {
|
||||
@ -30,7 +30,7 @@ switch (num) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a switch statement to set `answer` for the following conditions:
|
||||
Escreva a instrução switch para definir `answer` para as seguintes condições:
|
||||
`a` - `apple`
|
||||
`b` - `bird`
|
||||
`c` - `cat`
|
||||
@ -38,49 +38,49 @@ Write a switch statement to set `answer` for the following conditions:
|
||||
|
||||
# --hints--
|
||||
|
||||
`switchOfStuff("a")` should return the string `apple`
|
||||
`switchOfStuff("a")` deve retornar a string `apple`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('a') === 'apple');
|
||||
```
|
||||
|
||||
`switchOfStuff("b")` should return the string `bird`
|
||||
`switchOfStuff("b")` deve retornar a string `bird`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('b') === 'bird');
|
||||
```
|
||||
|
||||
`switchOfStuff("c")` should return the string `cat`
|
||||
`switchOfStuff("c")` deve retornar a string `cat`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('c') === 'cat');
|
||||
```
|
||||
|
||||
`switchOfStuff("d")` should return the string `stuff`
|
||||
`switchOfStuff("d")` deve retornar a string `stuff`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('d') === 'stuff');
|
||||
```
|
||||
|
||||
`switchOfStuff(4)` should return the string `stuff`
|
||||
`switchOfStuff(4)` deve retornar a string `stuff`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff(4) === 'stuff');
|
||||
```
|
||||
|
||||
You should not use any `if` or `else` statements
|
||||
Você não deve usar nenhuma das instruções `if` ou `else`
|
||||
|
||||
```js
|
||||
assert(!/else/g.test(code) || !/if/g.test(code));
|
||||
```
|
||||
|
||||
You should use a `default` statement
|
||||
Você deve usar a instrução `default`
|
||||
|
||||
```js
|
||||
assert(switchOfStuff('string-to-trigger-default-case') === 'stuff');
|
||||
```
|
||||
|
||||
You should have at least 3 `break` statements
|
||||
Você deve ter pelo menos 3 instruções `break`
|
||||
|
||||
```js
|
||||
assert(code.match(/break/g).length > 2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ed
|
||||
title: Appending Variables to Strings
|
||||
title: Adicionando Variáveis para Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmZfa'
|
||||
forumTopicId: 16656
|
||||
@ -9,9 +9,9 @@ dashedName: appending-variables-to-strings
|
||||
|
||||
# --description--
|
||||
|
||||
Just as we can build a string over multiple lines out of string <dfn>literals</dfn>, we can also append variables to a string using the plus equals (`+=`) operator.
|
||||
Assim como podemos construir uma string em várias linhas através das strings <dfn>literais</dfn>, nós também podemos adicionar as variáveis para a string usando o operador mais igual (`+=`).
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var anAdjective = "awesome!";
|
||||
@ -19,21 +19,21 @@ var ourStr = "freeCodeCamp is ";
|
||||
ourStr += anAdjective;
|
||||
```
|
||||
|
||||
`ourStr` would have the value `freeCodeCamp is awesome!`.
|
||||
`ourStr` teria o valor `freeCodeCamp is awesome!`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set `someAdjective` to a string of at least 3 characters and append it to `myStr` using the `+=` operator.
|
||||
Defina `someAdjective` para uma string de pelo menos 3 caracteres e adicione para `myStr` usando o operador `+=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`someAdjective` should be set to a string at least 3 characters long.
|
||||
`someAdjective` deve ser definida para uma string de pelo menos o tamanho de 3 caracteres.
|
||||
|
||||
```js
|
||||
assert(typeof someAdjective !== 'undefined' && someAdjective.length > 2);
|
||||
```
|
||||
|
||||
You should append `someAdjective` to `myStr` using the `+=` operator.
|
||||
Você deve adicionar `someAdjective` para `myStr` usando o operador `+=`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*someAdjective\s*/).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5ee127a03c3b35dd45426493
|
||||
title: Assigning the Value of One Variable to Another
|
||||
title: Atribua o Valor de Uma Variável para Outra
|
||||
challengeType: 1
|
||||
videoUrl: ''
|
||||
forumTopicId: 418265
|
||||
@ -9,7 +9,7 @@ dashedName: assigning-the-value-of-one-variable-to-another
|
||||
|
||||
# --description--
|
||||
|
||||
After a value is assigned to a variable using the <dfn>assignment</dfn> operator, you can assign the value of that variable to another variable using the <dfn>assignment</dfn> operator.
|
||||
Após um valor ser atribuído para uma variável usando o operador de <dfn>atribuição</dfn>, você pode atribuir o valor daquela variável para outra variável usando o operador de <dfn>atribuição</dfn>.
|
||||
|
||||
```js
|
||||
var myVar;
|
||||
@ -18,27 +18,27 @@ var myNum;
|
||||
myNum = myVar;
|
||||
```
|
||||
|
||||
The above declares a `myVar` variable with no value, then assigns it the value `5`. Next, a variable named `myNum` is declared with no value. Then, the contents of `myVar` (which is `5`) is assigned to the variable `myNum`. Now, `myNum` also has the value of `5`.
|
||||
O código acima declara uma variável `myVar` sem valor, e então atribui a ela o valor `5`. Em seguida, uma variável chamada `myNum` é declarada sem valor. Em seguida, o conteúdo de `myVar` (o qual é `5`) é atribuído para a variável `myNum`. Agora, `myNum` também possui o valor de `5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assign the contents of `a` to variable `b`.
|
||||
Atribua o conteúdo de `a` para a variável `b`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change code above the specified comment.
|
||||
Você não deve alterar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(/var a;/.test(code) && /a = 7;/.test(code) && /var b;/.test(code));
|
||||
```
|
||||
|
||||
`b` should have a value of `7`.
|
||||
`b` deve ter um valor de `7`.
|
||||
|
||||
```js
|
||||
assert(typeof b === 'number' && b === 7);
|
||||
```
|
||||
|
||||
`a` should be assigned to `b` with `=`.
|
||||
`a` deve ser atribuído para `b` com `=`.
|
||||
|
||||
```js
|
||||
assert(/b\s*=\s*a\s*/g.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c3
|
||||
title: Assignment with a Returned Value
|
||||
title: Atribuição com o Valor Retornado
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ce2pEtB'
|
||||
forumTopicId: 16658
|
||||
@ -9,29 +9,29 @@ dashedName: assignment-with-a-returned-value
|
||||
|
||||
# --description--
|
||||
|
||||
If you'll recall from our discussion of [Storing Values with the Assignment Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.
|
||||
Se você se lembrar de nossa discussão sobre [Armazenar valores com o Operador de Atribuição](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), tudo à direita do sinal de igual é resolvido antes do valor ser atribuído. Isso significa que podemos pegar o valor de retorno de uma função e atribuí-la a uma variável.
|
||||
|
||||
Assume we have pre-defined a function `sum` which adds two numbers together, then:
|
||||
Assuma que temos uma função pré-definida chamada `sum` a qual adiciona dois números, depois:
|
||||
|
||||
```js
|
||||
ourSum = sum(5, 12);
|
||||
```
|
||||
|
||||
will call `sum` function, which returns a value of `17` and assigns it to `ourSum` variable.
|
||||
chamará a função `sum`, a qual retorna o valor `17` e então atribui este valor à variável `ourSum`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Call the `processArg` function with an argument of `7` and assign its return value to the variable `processed`.
|
||||
Chame a função `processArg` com um argumento de `7` e atribui o retorno do seu valor para a variável `processed`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`processed` should have a value of `2`
|
||||
`processed` deve ter o valor `2`
|
||||
|
||||
```js
|
||||
assert(processed === 2);
|
||||
```
|
||||
|
||||
You should assign `processArg` to `processed`
|
||||
Você deve atribuir `processArg` para `processed`
|
||||
|
||||
```js
|
||||
assert(/processed\s*=\s*processArg\(\s*7\s*\)/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d0
|
||||
title: Build JavaScript Objects
|
||||
title: Construa Objetos JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWGkbtd'
|
||||
forumTopicId: 16769
|
||||
@ -9,13 +9,13 @@ dashedName: build-javascript-objects
|
||||
|
||||
# --description--
|
||||
|
||||
You may have heard the term `object` before.
|
||||
Você talvez tenha ouvido o termo `objeto` antes.
|
||||
|
||||
Objects are similar to `arrays`, except that instead of using indexes to access and modify their data, you access the data in objects through what are called `properties`.
|
||||
Objetos são similares a `arrays`, exceto que, ao invés de usar índices para acessar e modificar seus dados, você acessa os dados em objetos através do que se chama `propriedades`.
|
||||
|
||||
Objects are useful for storing data in a structured way, and can represent real world objects, like a cat.
|
||||
Objetos são úteis para armazenar dados de forma estruturada e podem representar objetos do mundo real, como um gato.
|
||||
|
||||
Here's a sample cat object:
|
||||
Aqui está um exemplo de objeto gato:
|
||||
|
||||
```js
|
||||
var cat = {
|
||||
@ -26,7 +26,7 @@ var cat = {
|
||||
};
|
||||
```
|
||||
|
||||
In this example, all the properties are stored as strings, such as - `name`, `legs`, and `tails`. However, you can also use numbers as properties. You can even omit the quotes for single-word string properties, as follows:
|
||||
Neste exemplo, todas as propriedades são armazenadas como strings, como - `name`, `legs`e `tails`. Porém, você também pode usar números como propriedades. Você pode até omitir as aspas para propriedades de string com uma única palavra, da seguinte forma:
|
||||
|
||||
```js
|
||||
var anotherObject = {
|
||||
@ -36,17 +36,17 @@ var anotherObject = {
|
||||
};
|
||||
```
|
||||
|
||||
However, if your object has any non-string properties, JavaScript will automatically typecast them as strings.
|
||||
No entanto, se seu objeto tem quaisquer propriedades que não seja string, o JavaScript irá automaticamente definir seus tipos como strings.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Make an object that represents a dog called `myDog` which contains the properties `name` (a string), `legs`, `tails` and `friends`.
|
||||
Faça um objeto que representa um cachorro chamado `myDog` que contém as propriedades `name` (uma string), `legs`, `tails` e `friends`.
|
||||
|
||||
You can set these object properties to whatever values you want, as long as `name` is a string, `legs` and `tails` are numbers, and `friends` is an array.
|
||||
Você pode definir essas propriedades do objeto para os valores que deseja, contanto que `name` seja uma string, `legs` e `tails` são números, e `friends` é um array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDog` should contain the property `name` and it should be a `string`.
|
||||
`myDog` deve conter a propriedade `name` e deve ser uma `string`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -64,7 +64,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` should contain the property `legs` and it should be a `number`.
|
||||
`myDog` deve conter a propriedade `name` e deve ser uma `string`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -82,7 +82,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` should contain the property `tails` and it should be a `number`.
|
||||
`myDog` deve conter a propriedade `tails` e deve ser um `número`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -100,7 +100,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` should contain the property `friends` and it should be an `array`.
|
||||
`myDog` deve conter a propriedade `friends` e deve ser um `array`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -118,7 +118,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myDog` should only contain all the given properties.
|
||||
`myDog` deve conter apenas todas as propriedades fornecidas.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244dc
|
||||
title: Chaining If Else Statements
|
||||
title: Encadeando Instruções If Else
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/caeJgsw'
|
||||
forumTopicId: 16772
|
||||
@ -9,7 +9,7 @@ dashedName: chaining-if-else-statements
|
||||
|
||||
# --description--
|
||||
|
||||
`if/else` statements can be chained together for complex logic. Here is <dfn>pseudocode</dfn> of multiple chained `if` / `else if` statements:
|
||||
`if/else` instruções podem ser encadeadas por uma lógica complexa. Aqui está o <dfn>pseudocódigo</dfn> de várias instruções encadeadas `if` / `else`:
|
||||
|
||||
```js
|
||||
if (condition1) {
|
||||
@ -26,89 +26,89 @@ if (condition1) {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write chained `if`/`else if` statements to fulfill the following conditions:
|
||||
Escreva instruções encadeadas `if`/`else` para atender as seguintes condições:
|
||||
|
||||
`num < 5` - return `Tiny`
|
||||
`num < 10` - return `Small`
|
||||
`num < 15` - return `Medium`
|
||||
`num < 20` - return `Large`
|
||||
`num >= 20` - return `Huge`
|
||||
`num < 5` - retorna `Tiny`
|
||||
`num < 10` - retorna `Small`
|
||||
`num < 15` - retorna `Medium`
|
||||
`num < 20` - retorna `Large`
|
||||
`num >= 20` - retorna `Huge`
|
||||
|
||||
# --hints--
|
||||
|
||||
You should have at least four `else` statements
|
||||
Você deve ter pelo menos quatro instruções `else`
|
||||
|
||||
```js
|
||||
assert(code.match(/else/g).length > 3);
|
||||
```
|
||||
|
||||
You should have at least four `if` statements
|
||||
Você deve ter pelo menos quatro instruções `if`
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length > 3);
|
||||
```
|
||||
|
||||
You should have at least one `return` statement
|
||||
Você deve ter pelo menos um comando `return`
|
||||
|
||||
```js
|
||||
assert(code.match(/return/g).length >= 1);
|
||||
```
|
||||
|
||||
`testSize(0)` should return the string `Tiny`
|
||||
`testSize(0)` deve retornar a string `Tiny`
|
||||
|
||||
```js
|
||||
assert(testSize(0) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(4)` should return the string `Tiny`
|
||||
`testSize(4)` deve retornar a string `Tiny`
|
||||
|
||||
```js
|
||||
assert(testSize(4) === 'Tiny');
|
||||
```
|
||||
|
||||
`testSize(5)` should return the string `Small`
|
||||
`testSize(5)` deve retornar a string `Small`
|
||||
|
||||
```js
|
||||
assert(testSize(5) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(8)` should return the string `Small`
|
||||
`testSize(8)` deve retornar a string `Small`
|
||||
|
||||
```js
|
||||
assert(testSize(8) === 'Small');
|
||||
```
|
||||
|
||||
`testSize(10)` should return the string `Medium`
|
||||
`testSize(10)` deve retornar a string `Medium`
|
||||
|
||||
```js
|
||||
assert(testSize(10) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(14)` should return the string `Medium`
|
||||
`testSize(14)` deve retornar a string `Medium`
|
||||
|
||||
```js
|
||||
assert(testSize(14) === 'Medium');
|
||||
```
|
||||
|
||||
`testSize(15)` should return the string `Large`
|
||||
`testSize(15)` deve retornar a string `Large`
|
||||
|
||||
```js
|
||||
assert(testSize(15) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(17)` should return the string `Large`
|
||||
`testSize(17)` deve retornar a string `Large`
|
||||
|
||||
```js
|
||||
assert(testSize(17) === 'Large');
|
||||
```
|
||||
|
||||
`testSize(20)` should return the string `Huge`
|
||||
`testSize(20)` deve retornar a string `Huge`
|
||||
|
||||
```js
|
||||
assert(testSize(20) === 'Huge');
|
||||
```
|
||||
|
||||
`testSize(25)` should return the string `Huge`
|
||||
`testSize(25)` deve retornar a string `Huge`
|
||||
|
||||
```js
|
||||
assert(testSize(25) === 'Huge');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c441eddfaeb4bdef
|
||||
title: Comment Your JavaScript Code
|
||||
title: Comente seu código JavaScript
|
||||
challengeType: 1
|
||||
removeComments: false
|
||||
videoUrl: 'https://scrimba.com/c/c7ynnTp'
|
||||
@ -10,38 +10,38 @@ dashedName: comment-your-javascript-code
|
||||
|
||||
# --description--
|
||||
|
||||
Comments are lines of code that JavaScript will intentionally ignore. Comments are a great way to leave notes to yourself and to other people who will later need to figure out what that code does.
|
||||
Comentários são linhas de código que JavaScript irá intencionalmente ignorar. Os comentários são uma ótima maneira de deixar anotações para você mesmo e para outras pessoas que mais tarde precisarão descobrir o que esse código faz.
|
||||
|
||||
There are two ways to write comments in JavaScript:
|
||||
Existem duas maneiras de escrever comentários em JavaScript:
|
||||
|
||||
Using `//` will tell JavaScript to ignore the remainder of the text on the current line. This is an in-line comment:
|
||||
Usando `//` dirá ao JavaScript para ignorar o resto do texto na linha atual. Isso é um comentário de uma linha:
|
||||
|
||||
```js
|
||||
// This is an in-line comment.
|
||||
```
|
||||
|
||||
You can make a multi-line comment beginning with `/*` and ending with `*/`. This is a multi-line comment:
|
||||
Você pode fazer um comentário de mais de uma linha, começando com `/*` e terminando com `*/`. Este é um comentário em várias linha:
|
||||
|
||||
```js
|
||||
/* This is a
|
||||
multi-line comment */
|
||||
```
|
||||
|
||||
**NOTE:** As you write code, you should regularly add comments to clarify the function of parts of your code. Good commenting can help communicate the intent of your code—both for others *and* for your future self.
|
||||
**NOTA:** À medida que você escreve código, você deve adicionar comentários regularmente, para esclarecer a função de partes do seu código. Um bom comentário pode ajudar a comunicar a intenção do seu código — tanto para os outros *quanto* para você mesmo no futuro.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Try creating one of each type of comment.
|
||||
Tente criar cada um dos tipos de comentários.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should create a `//` style comment that contains at least five letters.
|
||||
Você deve criar um comentário de uma linha (`//`) que contenha pelo menos cinco letras.
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\/)...../g));
|
||||
```
|
||||
|
||||
You should create a `/* */` style comment that contains at least five letters.
|
||||
Você deve criar um comentário de várias linhas (`/* */`) que contenha pelo menos cinco letras.
|
||||
|
||||
```js
|
||||
assert(code.match(/(\/\*)([^\/]{5,})(?=\*\/)/gm));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d0
|
||||
title: Comparison with the Equality Operator
|
||||
title: Comparação com o Operador de Igualdade
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKyVMAL'
|
||||
forumTopicId: 16784
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-equality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
There are many <dfn>comparison operators</dfn> in JavaScript. All of these operators return a boolean `true` or `false` value.
|
||||
Há muitos <dfn>operadores de comparação</dfn> em JavaScript. Todos esses operadores retornam um valor booleano `true` ou `false`.
|
||||
|
||||
The most basic operator is the equality operator `==`. The equality operator compares two values and returns `true` if they're equivalent or `false` if they are not. Note that equality is different from assignment (`=`), which assigns the value on the right of the operator to a variable on the left.
|
||||
O operador mais básico é o operador de igualdade `==`. O operador de igualdade compara dois valores e retorna `true` se eles são equivalentes ou `false` se não são. Observe que a igualdade é diferente de atribuição (`=`), que atribui o valor à direita do operador para uma variável à esquerda.
|
||||
|
||||
```js
|
||||
function equalityTest(myVal) {
|
||||
@ -22,7 +22,7 @@ function equalityTest(myVal) {
|
||||
}
|
||||
```
|
||||
|
||||
If `myVal` is equal to `10`, the equality operator returns `true`, so the code in the curly braces will execute, and the function will return `Equal`. Otherwise, the function will return `Not Equal`. In order for JavaScript to compare two different <dfn>data types</dfn> (for example, `numbers` and `strings`), it must convert one type to another. This is known as Type Coercion. Once it does, however, it can compare terms as follows:
|
||||
Se `myVal` é igual a `10`, o operador de igualdade retorna `true`, assim o código nas chaves será executado e a função retornará `Equal`. Caso contrário, a função retornará `Not Equal`. Para que JavaScript possa comparar dois <dfn>tipos de dados</dfn> diferentes (por exemplo, `números` e `strings`), deve converter um tipo para outro. Isto é conhecido como Coerção do Tipo (casting ou type coercion). No entanto, uma vez que o faça, pode comparar os termos da seguinte forma:
|
||||
|
||||
```js
|
||||
1 == 1
|
||||
@ -31,33 +31,33 @@ If `myVal` is equal to `10`, the equality operator returns `true`, so the code i
|
||||
"3" == 3
|
||||
```
|
||||
|
||||
In order, these expressions would evaluate to `true`, `false`, `true`, and `true`.
|
||||
Em ordem, essas expressões seriam avaliadas à `true`, `false`, `true` e `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the equality operator to the indicated line so that the function will return the string `Equal` when `val` is equivalent to `12`.
|
||||
Adicione o operador de igualdade à linha indicada para que a função retorne a string `Equal` quando `val` for equivalente a `12`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testEqual(10)` should return the string `Not Equal`
|
||||
`testEqual(10)` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testEqual(12)` should return the string `Equal`
|
||||
`testEqual(12)` deve retornar a string `Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual(12) === 'Equal');
|
||||
```
|
||||
|
||||
`testEqual("12")` should return the string `Equal`
|
||||
`testEqual("12")` deve retornar a string `Equal`
|
||||
|
||||
```js
|
||||
assert(testEqual('12') === 'Equal');
|
||||
```
|
||||
|
||||
You should use the `==` operator
|
||||
Você deve utilizar o operador `==`
|
||||
|
||||
```js
|
||||
assert(code.match(/==/g) && !code.match(/===/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d4
|
||||
title: Comparison with the Greater Than Operator
|
||||
title: Comparação com o Operador Maior Que
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cp6GbH4'
|
||||
forumTopicId: 16786
|
||||
@ -9,11 +9,11 @@ dashedName: comparison-with-the-greater-than-operator
|
||||
|
||||
# --description--
|
||||
|
||||
The greater than operator (`>`) compares the values of two numbers. If the number to the left is greater than the number to the right, it returns `true`. Otherwise, it returns `false`.
|
||||
O operador maior que (`>`) compara os valores de dois números. Se o número para a esquerda for maior que o número à direita, ele retorna `true`. Caso contrário, ele retorna `false`.
|
||||
|
||||
Like the equality operator, the greater than operator will convert data types of values while comparing.
|
||||
Tal como o operador de igualdade, o operador maior que converterá os tipos de dados de valores enquanto compara.
|
||||
|
||||
**Examples**
|
||||
**Exemplos**
|
||||
|
||||
```js
|
||||
5 > 3
|
||||
@ -22,57 +22,57 @@ Like the equality operator, the greater than operator will convert data types of
|
||||
'1' > 9
|
||||
```
|
||||
|
||||
In order, these expressions would evaluate to `true`, `true`, `false`, and `false`.
|
||||
Em ordem, essas expressões seriam iguais à `true`, `false`, `true` e `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the greater than operator to the indicated lines so that the return statements make sense.
|
||||
Adicione o operador maior que para indicar as linhas indicadas para que as instruções de retorno façam sentido.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterThan(0)` should return the string `10 or Under`
|
||||
`testGreaterThan(0)` deve retornar a string `10 or Under`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(0) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(10)` should return the string `10 or Under`
|
||||
`testGreaterThan(10)` deve retornar a string `10 or Under`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(10) === '10 or Under');
|
||||
```
|
||||
|
||||
`testGreaterThan(11)` should return the string `Over 10`
|
||||
`testGreaterThan(11)` deve retornar a string `Over 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(11) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(99)` should return the string `Over 10`
|
||||
`testGreaterThan(99)` deve retornar a string `Over 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(99) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(100)` should return the string `Over 10`
|
||||
`testGreaterThan(100)` deve retornar a string `Over 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(100) === 'Over 10');
|
||||
```
|
||||
|
||||
`testGreaterThan(101)` should return the string `Over 100`
|
||||
`testGreaterThan(101)` deve retornar a string `Over 100`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(101) === 'Over 100');
|
||||
```
|
||||
|
||||
`testGreaterThan(150)` should return the string `Over 100`
|
||||
`testGreaterThan(150)` deve retornar a string `Over 100`
|
||||
|
||||
```js
|
||||
assert(testGreaterThan(150) === 'Over 100');
|
||||
```
|
||||
|
||||
You should use the `>` operator at least twice
|
||||
Você deve usar o operador `>` pelo menos duas vezes
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>\s*('|")*\d+('|")*/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d5
|
||||
title: Comparison with the Greater Than Or Equal To Operator
|
||||
title: Comparação com o Operador Maior ou Igual
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KBqtV'
|
||||
forumTopicId: 16785
|
||||
@ -9,11 +9,11 @@ dashedName: comparison-with-the-greater-than-or-equal-to-operator
|
||||
|
||||
# --description--
|
||||
|
||||
The greater than or equal to operator (`>=`) compares the values of two numbers. If the number to the left is greater than or equal to the number to the right, it returns `true`. Otherwise, it returns `false`.
|
||||
O operador maior ou igual que (`>`) compara os valores de dois números. Se o número à esquerda é maior ou igual ao número à direita, ele retorna `verdadeiro`. Caso contrário, ele retornará `false`.
|
||||
|
||||
Like the equality operator, the greater than or equal to operator will convert data types while comparing.
|
||||
Tal como o operador de igualdade, o operador maior que converterá os tipos de dados de valores enquanto compara.
|
||||
|
||||
**Examples**
|
||||
**Exemplos**
|
||||
|
||||
```js
|
||||
6 >= 6
|
||||
@ -22,57 +22,57 @@ Like the equality operator, the greater than or equal to operator will convert d
|
||||
'7' >= 9
|
||||
```
|
||||
|
||||
In order, these expressions would evaluate to `true`, `true`, `false`, and `false`.
|
||||
Em ordem, essas expressões seriam iguais à `true`, `true`, `false` e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the greater than or equal to operator to the indicated lines so that the return statements make sense.
|
||||
Adicione o operador maior ou igual que para indicar as linhas indicadas para que as instruções de retorno façam sentido.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testGreaterOrEqual(0)` should return the string `Less than 10`
|
||||
`testGreaterOrEqual(0)` deve retornar a string `Less than 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(0) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(9)` should return the string `Less than 10`
|
||||
`testGreaterOrEqual(9)` deve retornar a string `Less than 10`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(9) === 'Less than 10');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(10)` should return the string `10 or Over`
|
||||
`testGreaterOrEqual(10)` deve retornar a string `10 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(10) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(11)` should return the string `10 or Over`
|
||||
`testGreaterOrEqual(11)` deve retornar a string `10 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(11) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(19)` should return the string `10 or Over`
|
||||
`testGreaterOrEqual(19)` deve retornar a string `10 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(19) === '10 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(100)` should return the string `20 or Over`
|
||||
`testGreaterOrEqual(100)` deve retornar a string `20 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(100) === '20 or Over');
|
||||
```
|
||||
|
||||
`testGreaterOrEqual(21)` should return the string `20 or Over`
|
||||
`testGreaterOrEqual(21)` deve retornar a string `20 or Over`
|
||||
|
||||
```js
|
||||
assert(testGreaterOrEqual(21) === '20 or Over');
|
||||
```
|
||||
|
||||
You should use the `>=` operator at least twice
|
||||
Você deve usar o operador `>=` pelo menos duas vezes
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*>=\s*('|")*\d+('|")*/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d2
|
||||
title: Comparison with the Inequality Operator
|
||||
title: Comparação com o operador de desigualdade
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cdBm9Sr'
|
||||
forumTopicId: 16787
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-inequality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
The inequality operator (`!=`) is the opposite of the equality operator. It means not equal and returns `false` where equality would return `true` and *vice versa*. Like the equality operator, the inequality operator will convert data types of values while comparing.
|
||||
O operador de desigualdade (`!=`) é o oposto do operador de igualdade. Significa que não é igual e retorna `falso` onde a igualdade retornaria `verdadeiro` e *vice-versa*. Tal como o operador de igualdade, o operador de desigualdade converterá os tipos de dados de valores enquanto compara.
|
||||
|
||||
**Examples**
|
||||
**Exemplos**
|
||||
|
||||
```js
|
||||
1 != 2
|
||||
@ -21,45 +21,45 @@ The inequality operator (`!=`) is the opposite of the equality operator. It mean
|
||||
0 != false
|
||||
```
|
||||
|
||||
In order, these expressions would evaluate to `true`, `false`, `false`, `false`, and `false`.
|
||||
Em ordem, essas expressões seriam iguais à `true`, `false`, `false`, `false` e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the inequality operator `!=` in the `if` statement so that the function will return the string `Not Equal` when `val` is not equivalent to `99`
|
||||
Adicione o operador de desigualdade `!=` na instrução `if` para que a função retorne a string `Not Equal` quando `val` não for equivalente a `99`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testNotEqual(99)` should return the string `Equal`
|
||||
`testNotEqual(99)` deve retornar a string `Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual(99) === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("99")` should return the string `Equal`
|
||||
`testNotEqual("99")` deve retornar a string `Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('99') === 'Equal');
|
||||
```
|
||||
|
||||
`testNotEqual(12)` should return the string `Not Equal`
|
||||
`testNotEqual(12)` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("12")` should return the string `Not Equal`
|
||||
`testNotEqual("12")` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('12') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testNotEqual("bob")` should return the string `Not Equal`
|
||||
`testNotEqual("bob")` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
You should use the `!=` operator
|
||||
Você deve usar o operador `!=`
|
||||
|
||||
```js
|
||||
assert(code.match(/(?!!==)!=/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d6
|
||||
title: Comparison with the Less Than Operator
|
||||
title: Comparação com o Operador Menor Que
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVRWtB'
|
||||
forumTopicId: 16789
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-less-than-operator
|
||||
|
||||
# --description--
|
||||
|
||||
The less than operator (`<`) compares the values of two numbers. If the number to the left is less than the number to the right, it returns `true`. Otherwise, it returns `false`. Like the equality operator, the less than operator converts data types while comparing.
|
||||
O operador menor que (`<`) compara os valores de dois números. Se o número a esquerda for menos que o número à direita, retornará `true`. Caso contrário, retorna `false`. Assim como o operador de igualdade, o operador menor que converte os tipos de dados enquando compara.
|
||||
|
||||
**Examples**
|
||||
**Exemplos**
|
||||
|
||||
```js
|
||||
2 < 5
|
||||
@ -21,51 +21,51 @@ The less than operator (`<`) compares the values of two numbers. If the number t
|
||||
'8' < 4
|
||||
```
|
||||
|
||||
In order, these expressions would evaluate to `true`, `true`, `false`, `false`, and `false`.
|
||||
Em ordem, essas expressões seriam igual à `true`, `true`, `false`, `false` e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the less than operator to the indicated lines so that the return statements make sense.
|
||||
Adicione o operador menor que para indicar as linhas para que a instrução de retorno faça sentido.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessThan(0)` should return the string `Under 25`
|
||||
`testLessThan(0)` deve retornar a string `Under 25`
|
||||
|
||||
```js
|
||||
assert(testLessThan(0) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(24)` should return the string `Under 25`
|
||||
`testLessThan(24)` deve retornar a string `Under 25`
|
||||
|
||||
```js
|
||||
assert(testLessThan(24) === 'Under 25');
|
||||
```
|
||||
|
||||
`testLessThan(25)` should return the string `Under 55`
|
||||
`testLessThan(25)` deve retornar a string `Under 55`
|
||||
|
||||
```js
|
||||
assert(testLessThan(25) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(54)` should return the string `Under 55`
|
||||
`testLessThan(54)` deve retornar a string `Under 55`
|
||||
|
||||
```js
|
||||
assert(testLessThan(54) === 'Under 55');
|
||||
```
|
||||
|
||||
`testLessThan(55)` should return the string `55 or Over`
|
||||
`testLessThan(55)` deve retornar a string `55 or Over`
|
||||
|
||||
```js
|
||||
assert(testLessThan(55) === '55 or Over');
|
||||
```
|
||||
|
||||
`testLessThan(99)` should return the string `55 or Over`
|
||||
`testLessThan(99)` deve retornar a string `55 or Over`
|
||||
|
||||
```js
|
||||
assert(testLessThan(99) === '55 or Over');
|
||||
```
|
||||
|
||||
You should use the `<` operator at least twice
|
||||
Você deve usar o operador `<` pelo menos duas vezes
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<\s*('|")*\d+('|")*/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d7
|
||||
title: Comparison with the Less Than Or Equal To Operator
|
||||
title: Comparação com o Operador Menor ou Igual
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNVR7Am'
|
||||
forumTopicId: 16788
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-less-than-or-equal-to-operator
|
||||
|
||||
# --description--
|
||||
|
||||
The less than or equal to operator (`<=`) compares the values of two numbers. If the number to the left is less than or equal to the number to the right, it returns `true`. If the number on the left is greater than the number on the right, it returns `false`. Like the equality operator, the less than or equal to operator converts data types.
|
||||
O operador menor ou igual (`<=`) compara os valores de dois números. Se o número à esquerda for menor ou igual ao número à direita, retornará `true`. Se o número a esquerda for maior que o número a direita, retornará `false`. Assim como o operador de igualdade, o operador de menor ou igual que converte os tipos de dados.
|
||||
|
||||
**Examples**
|
||||
**Exemplos**
|
||||
|
||||
```js
|
||||
4 <= 5
|
||||
@ -21,57 +21,57 @@ The less than or equal to operator (`<=`) compares the values of two numbers. If
|
||||
'8' <= 4
|
||||
```
|
||||
|
||||
In order, these expressions would evaluate to `true`, `true`, `true`, `false`, and `false`.
|
||||
Em ordem, essas expressões seriam iguais à `true`, `true`, `true`, `false` e `false`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the less than or equal to operator to the indicated lines so that the return statements make sense.
|
||||
Adicione o operador menor ou igual que para indicar as linhas para que as instruções de retorno façam sentido.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testLessOrEqual(0)` should return the string `Smaller Than or Equal to 12`
|
||||
`testLessOrEqual(0)` deve retornar a string `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(0) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(11)` should return the string `Smaller Than or Equal to 12`
|
||||
`testLessOrEqual(11)` deve retornar a string `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(11) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(12)` should return the string `Smaller Than or Equal to 12`
|
||||
`testLessOrEqual(12)` deve retornar a string `Smaller Than or Equal to 12`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(12) === 'Smaller Than or Equal to 12');
|
||||
```
|
||||
|
||||
`testLessOrEqual(23)` should return the string `Smaller Than or Equal to 24`
|
||||
`testLessOrEqual(23)` deve retornar a string `Smaller Than or Equal to 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(23) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(24)` should return the string `Smaller Than or Equal to 24`
|
||||
`testLessOrEqual(24)` deve retornar a string `Smaller Than or Equal to 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(24) === 'Smaller Than or Equal to 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(25)` should return the string `More Than 24`
|
||||
`testLessOrEqual(25)` deve retornar a string `More than 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(25) === 'More Than 24');
|
||||
```
|
||||
|
||||
`testLessOrEqual(55)` should return the string `More Than 24`
|
||||
`testLessOrEqual(55)` deve retornar a string `More than 24`
|
||||
|
||||
```js
|
||||
assert(testLessOrEqual(55) === 'More Than 24');
|
||||
```
|
||||
|
||||
You should use the `<=` operator at least twice
|
||||
Você deve usar o operador `<=` pelo menos duas vezes
|
||||
|
||||
```js
|
||||
assert(code.match(/val\s*<=\s*('|")*\d+('|")*/g).length > 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d1
|
||||
title: Comparison with the Strict Equality Operator
|
||||
title: Comparação com o Operador de Igualdade Estrita
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cy87atr'
|
||||
forumTopicId: 16790
|
||||
@ -9,46 +9,46 @@ dashedName: comparison-with-the-strict-equality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
Strict equality (`===`) is the counterpart to the equality operator (`==`). However, unlike the equality operator, which attempts to convert both values being compared to a common type, the strict equality operator does not perform a type conversion.
|
||||
Igualdade estrita (`===`) é a contrapartida do operador de igualdade (`==`). No entanto, ao contrário do operador de igualdade, que tenta converter ambos os valores em comparação a um tipo comum, o operador estrito de igualdade não realiza uma conversão de tipo.
|
||||
|
||||
If the values being compared have different types, they are considered unequal, and the strict equality operator will return false.
|
||||
Se os valores que são comparados tiverem valores diferentes, são considerados desiguais, e o operador de igualdade estrito retornará falso.
|
||||
|
||||
**Examples**
|
||||
**Exemplos**
|
||||
|
||||
```js
|
||||
3 === 3
|
||||
3 === '3'
|
||||
```
|
||||
|
||||
These conditions would return `true` and `false` respectively.
|
||||
Essas condições retornariam `true` e `false` respectivamente.
|
||||
|
||||
In the second example, `3` is a `Number` type and `'3'` is a `String` type.
|
||||
No segundo exemplo, `3` é um tipo de `Number` e `'3'` é um tipo `String`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the strict equality operator in the `if` statement so the function will return the string `Equal` when `val` is strictly equal to `7`
|
||||
Use o operador de igualdade estrito na instrução `if`, para que a função retorne a string `Equal` quando `val` for estritamente igual a `7`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrict(10)` should return the string `Not Equal`
|
||||
`testStrict(10)` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict(10) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrict(7)` should return the string `Equal`
|
||||
`testStrict(7)` deve retornar a string `Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict(7) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrict("7")` should return the string `Not Equal`
|
||||
`testStrict("7")` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrict('7') === 'Not Equal');
|
||||
```
|
||||
|
||||
You should use the `===` operator
|
||||
Você deve usar o operador `===`
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*===\s*\d+)|(\d+\s*===\s*val)/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d3
|
||||
title: Comparison with the Strict Inequality Operator
|
||||
title: Comparação com o Operador de Desigualdade Estrito
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cKekkUy'
|
||||
forumTopicId: 16791
|
||||
@ -9,9 +9,9 @@ dashedName: comparison-with-the-strict-inequality-operator
|
||||
|
||||
# --description--
|
||||
|
||||
The strict inequality operator (`!==`) is the logical opposite of the strict equality operator. It means "Strictly Not Equal" and returns `false` where strict equality would return `true` and *vice versa*. The strict inequality operator will not convert data types.
|
||||
O operador de desigualdade estrito (`!=`) é o oposto lógico do operador de igualdade estrito. Significa que "não é estritamente igual" e retorna `false` onde a igualdade estrita retornaria `true` e *vice-versa*. O operador de desigualdade estrita não converterá tipos de dados.
|
||||
|
||||
**Examples**
|
||||
**Exemplos**
|
||||
|
||||
```js
|
||||
3 !== 3
|
||||
@ -19,39 +19,39 @@ The strict inequality operator (`!==`) is the logical opposite of the strict equ
|
||||
4 !== 3
|
||||
```
|
||||
|
||||
In order, these expressions would evaluate to `false`, `true`, and `true`.
|
||||
Em ordem, essas expressões seriam iguais à `false`, `true` e `true`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add the strict inequality operator to the `if` statement so the function will return the string `Not Equal` when `val` is not strictly equal to `17`
|
||||
Adicione o operador de desigualdade estrito ao comando `if` para que a função retorne a string `Not Equal` quando `val` não é estritamente igual a `17`
|
||||
|
||||
# --hints--
|
||||
|
||||
`testStrictNotEqual(17)` should return the string `Equal`
|
||||
`testStrictNotEqual(17)` deve retornar a string `Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(17) === 'Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("17")` should return the string `Not Equal`
|
||||
`testStrictNotEqual("17")` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('17') === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual(12)` should return the string `Not Equal`
|
||||
`testStrictNotEqual(12)` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual(12) === 'Not Equal');
|
||||
```
|
||||
|
||||
`testStrictNotEqual("bob")` should return the string `Not Equal`
|
||||
`testStrictNotEqual("bob")` deve retornar a string `Not Equal`
|
||||
|
||||
```js
|
||||
assert(testStrictNotEqual('bob') === 'Not Equal');
|
||||
```
|
||||
|
||||
You should use the `!==` operator
|
||||
Você deve usar o operador `!==`
|
||||
|
||||
```js
|
||||
assert(code.match(/(val\s*!==\s*\d+)|(\d+\s*!==\s*val)/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d8
|
||||
title: Comparisons with the Logical And Operator
|
||||
title: Comparações com o Operador lógico E
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvbRVtr'
|
||||
forumTopicId: 16799
|
||||
@ -9,9 +9,9 @@ dashedName: comparisons-with-the-logical-and-operator
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you will need to test more than one thing at a time. The <dfn>logical and</dfn> operator (`&&`) returns `true` if and only if the <dfn>operands</dfn> to the left and right of it are true.
|
||||
Às vezes você precisará testar mais de uma coisa de cada vez. O <dfn>operador lógico e</dfn>(`&&`) retornará `true` apenas se os <dfn>operadores</dfn> a esquerda e à direita são verdadeiros.
|
||||
|
||||
The same effect could be achieved by nesting an if statement inside another if:
|
||||
O mesmo efeito pode ser alcançado aninhando uma instrução if dentro de outro if:
|
||||
|
||||
```js
|
||||
if (num > 5) {
|
||||
@ -22,7 +22,7 @@ if (num > 5) {
|
||||
return "No";
|
||||
```
|
||||
|
||||
will only return `Yes` if `num` is greater than `5` and less than `10`. The same logic can be written as:
|
||||
só retornará `Yes` se `num` é maior que `5` e menor que `10`. A mesma lógica pode ser escrita como:
|
||||
|
||||
```js
|
||||
if (num > 5 && num < 10) {
|
||||
@ -33,65 +33,65 @@ return "No";
|
||||
|
||||
# --instructions--
|
||||
|
||||
Replace the two if statements with one statement, using the `&&` operator, which will return the string `Yes` if `val` is less than or equal to `50` and greater than or equal to `25`. Otherwise, will return the string `No`.
|
||||
Substitua as duas instruções if por uma declaração, usando o operador `&&`, que irá retornar a string `Yes` se `val` for menor ou igual a `50` e maior ou igual a `25`. Caso contrário, retornará a string `No`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should use the `&&` operator once
|
||||
Você deve usar o operador `&&` uma vez
|
||||
|
||||
```js
|
||||
assert(code.match(/&&/g).length === 1);
|
||||
```
|
||||
|
||||
You should only have one `if` statement
|
||||
Você deve ter apenas um comando `if`
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalAnd(0)` should return the string `No`
|
||||
`testLogicalAnd(0)` deve retornar a string `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(0) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(24)` should return the string `No`
|
||||
`testLogicalAnd(24)` deve retornar a string `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(24) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(25)` should return the string `Yes`
|
||||
`testLogicalAnd(25)` deve retornar a string `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(25) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(30)` should return the string `Yes`
|
||||
`testLogicalAnd(30)` deve retornar a string `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(30) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(50)` should return the string `Yes`
|
||||
`testLogicalAnd(50)` deve retornar a string `Yes`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(50) === 'Yes');
|
||||
```
|
||||
|
||||
`testLogicalAnd(51)` should return the string `No`
|
||||
`testLogicalAnd(51)` deve retornar a string `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(51) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(75)` should return the string `No`
|
||||
`testLogicalAnd(75)` deve retornar a string `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(75) === 'No');
|
||||
```
|
||||
|
||||
`testLogicalAnd(80)` should return the string `No`
|
||||
`testLogicalAnd(80)` deve retornar a string `No`
|
||||
|
||||
```js
|
||||
assert(testLogicalAnd(80) === 'No');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244d9
|
||||
title: Comparisons with the Logical Or Operator
|
||||
title: Comparações com o Operador Lógico Ou
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cEPrGTN'
|
||||
forumTopicId: 16800
|
||||
@ -9,11 +9,11 @@ dashedName: comparisons-with-the-logical-or-operator
|
||||
|
||||
# --description--
|
||||
|
||||
The <dfn>logical or</dfn> operator (`||`) returns `true` if either of the <dfn>operands</dfn> is `true`. Otherwise, it returns `false`.
|
||||
O <dfn>operador lógico ou</dfn> (`||`) retorna `true` se qualquer um dos <dfn>operandos</dfn> for `true`. Caso contrário, retorna `false`.
|
||||
|
||||
The <dfn>logical or</dfn> operator is composed of two pipe symbols: (`||`). This can typically be found between your Backspace and Enter keys.
|
||||
O <dfn>operador lógico ou</dfn> é composto por dois símbolos de pipe: (`||`). Normalmente isso pode ser encontrado entre as teclas Backspace e Enter.
|
||||
|
||||
The pattern below should look familiar from prior waypoints:
|
||||
O padrão abaixo deve parecer familiar aos pontos da passagens anteriores:
|
||||
|
||||
```js
|
||||
if (num > 10) {
|
||||
@ -25,7 +25,7 @@ if (num < 5) {
|
||||
return "Yes";
|
||||
```
|
||||
|
||||
will return `Yes` only if `num` is between `5` and `10` (5 and 10 included). The same logic can be written as:
|
||||
retornará `Yes` apenas se `num` for entre `5` e `10` (5 e 10 incluídos). A mesma lógica pode ser escrita como:
|
||||
|
||||
```js
|
||||
if (num > 10 || num < 5) {
|
||||
@ -36,65 +36,65 @@ return "Yes";
|
||||
|
||||
# --instructions--
|
||||
|
||||
Combine the two `if` statements into one statement which returns the string `Outside` if `val` is not between `10` and `20`, inclusive. Otherwise, return the string `Inside`.
|
||||
Combine as duas instruções `if` em uma mesma instrução a qual retorna a string `Outside` se `val` não estiver entre `10` e `20`, inclusos 10 e 20. Caso contrário, retorna a string `Inside`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should use the `||` operator once
|
||||
Você deve usar o operador `||` uma vez
|
||||
|
||||
```js
|
||||
assert(code.match(/\|\|/g).length === 1);
|
||||
```
|
||||
|
||||
You should only have one `if` statement
|
||||
Você deve ter apenas uma instrução `if`
|
||||
|
||||
```js
|
||||
assert(code.match(/if/g).length === 1);
|
||||
```
|
||||
|
||||
`testLogicalOr(0)` should return the string `Outside`
|
||||
`testLogicalOr(0)` deve retornar a string `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(0) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(9)` should return the string `Outside`
|
||||
`testLogicalOr(9)` deve retornar a string `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(9) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(10)` should return the string `Inside`
|
||||
`testLogicalOr(10)` deve retornar a string `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(10) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(15)` should return the string `Inside`
|
||||
`testLogicalOr(15)` deve retornar a string `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(15) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(19)` should return the string `Inside`
|
||||
`testLogicalOr(19)` deve retornar a string `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(19) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(20)` should return the string `Inside`
|
||||
`testLogicalOr(20)` deve retornar a string `Inside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(20) === 'Inside');
|
||||
```
|
||||
|
||||
`testLogicalOr(21)` should return the string `Outside`
|
||||
`testLogicalOr(21)` deve retornar a string `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(21) === 'Outside');
|
||||
```
|
||||
|
||||
`testLogicalOr(25)` should return the string `Outside`
|
||||
`testLogicalOr(25)` deve retornar a string `Outside`
|
||||
|
||||
```js
|
||||
assert(testLogicalOr(25) === 'Outside');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244af
|
||||
title: Compound Assignment With Augmented Addition
|
||||
title: Atribuição Composta Com Adição Aumentada
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDR6LCb'
|
||||
forumTopicId: 16661
|
||||
@ -9,15 +9,15 @@ dashedName: compound-assignment-with-augmented-addition
|
||||
|
||||
# --description--
|
||||
|
||||
In programming, it is common to use assignments to modify the contents of a variable. Remember that everything to the right of the equals sign is evaluated first, so we can say:
|
||||
Na programação, é comum usar atribuições para modificar o conteúdo de uma variável. Lembre-se de que tudo à direita do sinal de igual é avaliado primeiro, para que possamos dizer:
|
||||
|
||||
```js
|
||||
myVar = myVar + 5;
|
||||
```
|
||||
|
||||
to add `5` to `myVar`. Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.
|
||||
para adicionar `5` a `myVar`. Como este é um padrão tão comum, existem operadores que realizam uma operação matemática e atribuição em um passo.
|
||||
|
||||
One such operator is the `+=` operator.
|
||||
Um desses operadores é o operador `+=`.
|
||||
|
||||
```js
|
||||
var myVar = 1;
|
||||
@ -25,39 +25,39 @@ myVar += 5;
|
||||
console.log(myVar);
|
||||
```
|
||||
|
||||
`6` would be displayed in the console.
|
||||
`6` seria exibido no console.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `+=` operator.
|
||||
Converta as atribuições para `a`, `b` e `c` para usar o operador `+=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should equal `15`.
|
||||
`a` deve ser igual a `15`.
|
||||
|
||||
```js
|
||||
assert(a === 15);
|
||||
```
|
||||
|
||||
`b` should equal `26`.
|
||||
`b` deve ser igual a `26`.
|
||||
|
||||
```js
|
||||
assert(b === 26);
|
||||
```
|
||||
|
||||
`c` should equal `19`.
|
||||
`c` deve ser igual a `19`.
|
||||
|
||||
```js
|
||||
assert(c === 19);
|
||||
```
|
||||
|
||||
You should use the `+=` operator for each variable.
|
||||
Você deve usar o operador `+=` para cada variável.
|
||||
|
||||
```js
|
||||
assert(code.match(/\+=/g).length === 3);
|
||||
```
|
||||
|
||||
You should not modify the code above the specified comment.
|
||||
Você não deve modificar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b2
|
||||
title: Compound Assignment With Augmented Division
|
||||
title: Atribuição Composta Com Divisão Aumentada
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvKT2'
|
||||
forumTopicId: 16659
|
||||
@ -9,13 +9,13 @@ dashedName: compound-assignment-with-augmented-division
|
||||
|
||||
# --description--
|
||||
|
||||
The `/=` operator divides a variable by another number.
|
||||
O operador `/=` divide uma variável por outro número.
|
||||
|
||||
```js
|
||||
myVar = myVar / 5;
|
||||
```
|
||||
|
||||
Will divide `myVar` by `5`. This can be rewritten as:
|
||||
Irá dividir `myVar` por `5`. Isto pode ser reescrito como:
|
||||
|
||||
```js
|
||||
myVar /= 5;
|
||||
@ -23,35 +23,35 @@ myVar /= 5;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `/=` operator.
|
||||
Converta as atribuições para `a`, `b` e `c` para usar o operador `/=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should equal `4`.
|
||||
`a` deve ser igual a `4`.
|
||||
|
||||
```js
|
||||
assert(a === 4);
|
||||
```
|
||||
|
||||
`b` should equal `27`.
|
||||
`b` deve ser igual a `27`.
|
||||
|
||||
```js
|
||||
assert(b === 27);
|
||||
```
|
||||
|
||||
`c` should equal `3`.
|
||||
`c` deve ser igual a `3`.
|
||||
|
||||
```js
|
||||
assert(c === 3);
|
||||
```
|
||||
|
||||
You should use the `/=` operator for each variable.
|
||||
Você deve usar o operador `/=` para cada variável.
|
||||
|
||||
```js
|
||||
assert(code.match(/\/=/g).length === 3);
|
||||
```
|
||||
|
||||
You should not modify the code above the specified comment.
|
||||
Você não deve modificar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b1
|
||||
title: Compound Assignment With Augmented Multiplication
|
||||
title: Atribuição Composta Com Multiplicação Aumentada
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c83vrfa'
|
||||
forumTopicId: 16662
|
||||
@ -9,13 +9,13 @@ dashedName: compound-assignment-with-augmented-multiplication
|
||||
|
||||
# --description--
|
||||
|
||||
The `*=` operator multiplies a variable by a number.
|
||||
O operador `*=` multiplica uma variável por um número.
|
||||
|
||||
```js
|
||||
myVar = myVar * 5;
|
||||
```
|
||||
|
||||
will multiply `myVar` by `5`. This can be rewritten as:
|
||||
irá multiplicar `myVar` por `5`. Isto pode ser reescrito como:
|
||||
|
||||
```js
|
||||
myVar *= 5;
|
||||
@ -23,35 +23,35 @@ myVar *= 5;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `*=` operator.
|
||||
Converta as atribuições para `a`, `b` e `c` para usar o operador `*=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should equal `25`.
|
||||
`a` deve ser igual a `25`.
|
||||
|
||||
```js
|
||||
assert(a === 25);
|
||||
```
|
||||
|
||||
`b` should equal `36`.
|
||||
`b` deve ser igual a `36`.
|
||||
|
||||
```js
|
||||
assert(b === 36);
|
||||
```
|
||||
|
||||
`c` should equal `46`.
|
||||
`c` deve ser igual a `46`.
|
||||
|
||||
```js
|
||||
assert(c === 46);
|
||||
```
|
||||
|
||||
You should use the `*=` operator for each variable.
|
||||
Você deve usar o operador `*=` para cada variável.
|
||||
|
||||
```js
|
||||
assert(code.match(/\*=/g).length === 3);
|
||||
```
|
||||
|
||||
You should not modify the code above the specified comment.
|
||||
Você não deve modificar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b0
|
||||
title: Compound Assignment With Augmented Subtraction
|
||||
title: Atribuição Composta Com Subtração Aumentada
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2Qv7AV'
|
||||
forumTopicId: 16660
|
||||
@ -9,13 +9,13 @@ dashedName: compound-assignment-with-augmented-subtraction
|
||||
|
||||
# --description--
|
||||
|
||||
Like the `+=` operator, `-=` subtracts a number from a variable.
|
||||
Como o operador `+=`, `-=` subtrai um número de uma variável.
|
||||
|
||||
```js
|
||||
myVar = myVar - 5;
|
||||
```
|
||||
|
||||
will subtract `5` from `myVar`. This can be rewritten as:
|
||||
irá subtrair `5` de `myVar`. Isto pode ser reescrito como:
|
||||
|
||||
```js
|
||||
myVar -= 5;
|
||||
@ -23,35 +23,35 @@ myVar -= 5;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Convert the assignments for `a`, `b`, and `c` to use the `-=` operator.
|
||||
Converta as atribuições para `a`, `b` e `c` para usar o operador `+=`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`a` should equal `5`.
|
||||
`a` deve ser igual a `5`.
|
||||
|
||||
```js
|
||||
assert(a === 5);
|
||||
```
|
||||
|
||||
`b` should equal `-6`.
|
||||
`b` deve ser igual a `-6`.
|
||||
|
||||
```js
|
||||
assert(b === -6);
|
||||
```
|
||||
|
||||
`c` should equal `2`.
|
||||
`c` deve ser igual a `2`.
|
||||
|
||||
```js
|
||||
assert(c === 2);
|
||||
```
|
||||
|
||||
You should use the `-=` operator for each variable.
|
||||
Você deve usar o operador `-=` para cada variável.
|
||||
|
||||
```js
|
||||
assert(code.match(/-=/g).length === 3);
|
||||
```
|
||||
|
||||
You should not modify the code above the specified comment.
|
||||
Você não deve modificar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b7
|
||||
title: Concatenating Strings with Plus Operator
|
||||
title: Concatenando Strings com Operador Mais
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNpM8AN'
|
||||
forumTopicId: 16802
|
||||
@ -9,48 +9,48 @@ dashedName: concatenating-strings-with-plus-operator
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, when the `+` operator is used with a `String` value, it is called the <dfn>concatenation</dfn> operator. You can build a new string out of other strings by <dfn>concatenating</dfn> them together.
|
||||
Em JavaScript, quando o operador `+` é usado com um valor de `String`, ele é chamado de operador de <dfn>concatenação</dfn>. Você pode construir uma nova string a partir de outras strings ao <dfn>concatenar</dfn> elas juntos.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
'My name is Alan,' + ' I concatenate.'
|
||||
```
|
||||
|
||||
**Note:** Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
|
||||
**Nota:** Cuidado com os espaços. A concatenação não adiciona espaços entre strings concatenadas, então você mesmo precisará adicioná-las.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. " + "I come second.";
|
||||
```
|
||||
|
||||
The string `I come first. I come second.` would be displayed in the console.
|
||||
A string `I come first. I come second.` seria exibida no console.
|
||||
# --instructions--
|
||||
|
||||
Build `myStr` from the strings `This is the start. ` and `This is the end.` using the `+` operator.
|
||||
Construa `myStr` a partir das strings `This is the start.` e `This is the end.` usando o operador `+`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` should have a value of the string `This is the start. This is the end.`
|
||||
`myStr` deve ter o valor da string `This is the start. This is the end.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the start. This is the end.');
|
||||
```
|
||||
|
||||
You should use the `+` operator to build `myStr`.
|
||||
Você deve usar o operador `+` para construir `myStr`.
|
||||
|
||||
```js
|
||||
assert(code.match(/(["']).*\1\s*\+\s*(["']).*\2/g));
|
||||
```
|
||||
|
||||
`myStr` should be created using the `var` keyword.
|
||||
`myStr` deve ser criado usando a palavra-chave `var`.
|
||||
|
||||
```js
|
||||
assert(/var\s+myStr/.test(code));
|
||||
```
|
||||
|
||||
You should assign the result to the `myStr` variable.
|
||||
Você deve atribuir o resultado à variável `myStr`.
|
||||
|
||||
```js
|
||||
assert(/myStr\s*=/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b8
|
||||
title: Concatenating Strings with the Plus Equals Operator
|
||||
title: Concatenando strings com o operador mais igual
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cbQmmC4'
|
||||
forumTopicId: 16803
|
||||
@ -9,32 +9,32 @@ dashedName: concatenating-strings-with-the-plus-equals-operator
|
||||
|
||||
# --description--
|
||||
|
||||
We can also use the `+=` operator to <dfn>concatenate</dfn> a string onto the end of an existing string variable. This can be very helpful to break a long string over several lines.
|
||||
Também podemos usar o operador `+=` para <dfn>concatenar</dfn> uma string no final de uma variável string existente. Isso pode ser muito útil para quebrar uma longa string em várias linhas.
|
||||
|
||||
**Note:** Watch out for spaces. Concatenation does not add spaces between concatenated strings, so you'll need to add them yourself.
|
||||
**Nota:** Cuidado com os espaços. A concatenação não adiciona espaços entre strings concatenadas, então você mesmo precisará adicioná-las.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourStr = "I come first. ";
|
||||
ourStr += "I come second.";
|
||||
```
|
||||
|
||||
`ourStr` now has a value of the string `I come first. I come second.`.
|
||||
`ourStr` agora deve ter como valor a string `I come first. I come second.`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Build `myStr` over several lines by concatenating these two strings: `This is the first sentence. ` and `This is the second sentence.` using the `+=` operator. Use the `+=` operator similar to how it is shown in the example. Start by assigning the first string to `myStr`, then add on the second string.
|
||||
Construa `myStr` sobre várias linhas concatenando essas duas strings: `Esta é a primeira frase.` e `Esta é a segunda frase.` usando o operador `+=`. Use o operador `+=` de modo semelhante a como aparece no exemplo. Comece atribuindo o primeiro texto para `myStr`, e então adicione o segundo texto.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` should have a value of the string `This is the first sentence. This is the second sentence.`
|
||||
`myStr` deve ter como valor a string `This is the first sentence. This is the second sentence.`
|
||||
|
||||
```js
|
||||
assert(myStr === 'This is the first sentence. This is the second sentence.');
|
||||
```
|
||||
|
||||
You should use the `+=` operator to build `myStr`.
|
||||
Você deve usar o operador `+=` para construir `myStr`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myStr\s*\+=\s*(["']).*\1/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b9
|
||||
title: Constructing Strings with Variables
|
||||
title: Construindo Strings com Variáveis
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqk8rf4'
|
||||
forumTopicId: 16805
|
||||
@ -9,30 +9,30 @@ dashedName: constructing-strings-with-variables
|
||||
|
||||
# --description--
|
||||
|
||||
Sometimes you will need to build a string, [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs) style. By using the concatenation operator (`+`), you can insert one or more variables into a string you're building.
|
||||
Às vezes você precisará construir uma string, no estilo [Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs). Usando o operador de concatenação (`+`), você pode inserir uma ou mais variáveis em uma string que você está construindo.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourName = "freeCodeCamp";
|
||||
var ourStr = "Hello, our name is " + ourName + ", how are you?";
|
||||
```
|
||||
|
||||
`ourStr` would have a value of the string `Hello, our name is freeCodeCamp, how are you?`.
|
||||
`ourStr` teria o valor da string `Hello, our name is freeCodeCamp, how are you?`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set `myName` to a string equal to your name and build `myStr` with `myName` between the strings `My name is ` and ` and I am well!`
|
||||
Defina `myName` para uma string igual ao seu nome e construa `myStr` com `myName` em duas strings: `My name is` e `and I am well!`
|
||||
|
||||
# --hints--
|
||||
|
||||
`myName` should be set to a string at least 3 characters long.
|
||||
`myName` deve ser definido para uma string de pelo menos 3 caracteres.
|
||||
|
||||
```js
|
||||
assert(typeof myName !== 'undefined' && myName.length > 2);
|
||||
```
|
||||
|
||||
You should use two `+` operators to build `myStr` with `myName` inside it.
|
||||
Você deve usar dois operadores `+` para construir `myStr` com `myName` dentro dele.
|
||||
|
||||
```js
|
||||
assert(code.match(/["']\s*\+\s*myName\s*\+\s*["']/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56105e7b514f539506016a5e
|
||||
title: Count Backwards With a For Loop
|
||||
title: Conte para Trás com um Laço For
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2R6BHa'
|
||||
forumTopicId: 16808
|
||||
@ -9,11 +9,11 @@ dashedName: count-backwards-with-a-for-loop
|
||||
|
||||
# --description--
|
||||
|
||||
A for loop can also count backwards, so long as we can define the right conditions.
|
||||
Um laço for também pode contar pra trás, contanto que possamos definir as condições certas.
|
||||
|
||||
In order to decrement by two each iteration, we'll need to change our initialization, condition, and final expression.
|
||||
Para decrementar em dois cada iteração, nós precisamos alterar nossa inicialização, condição e expressão final.
|
||||
|
||||
We'll start at `i = 10` and loop while `i > 0`. We'll decrement `i` by 2 each loop with `i -= 2`.
|
||||
Nós começaremos em `i = 10` e iterar enquanto `i > 0`. Nós decrementamos `i` por dois em cada iteração com `i -= 2`.
|
||||
|
||||
```js
|
||||
var ourArray = [];
|
||||
@ -22,27 +22,27 @@ for (var i = 10; i > 0; i -= 2) {
|
||||
}
|
||||
```
|
||||
|
||||
`ourArray` will now contain `[10,8,6,4,2]`. Let's change our initialization and final expression so we can count backwards by twos to create an array of descending odd numbers.
|
||||
`ourArray` agora vai conter `[10,8, 6,4,2]`. Vamos mudar nossa inicialização e expressão final para que possamos contar para trás em dois para criar um array de números ímpares decrescentes.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Push the odd numbers from 9 through 1 to `myArray` using a `for` loop.
|
||||
Adicione (push) os números ímpares de 9 até 1 para `myArray` usando um laço `for`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should be using a `for` loop for this.
|
||||
Você deve estar usando um laço `for` para isso.
|
||||
|
||||
```js
|
||||
assert(/for\s*\([^)]+?\)/.test(code));
|
||||
```
|
||||
|
||||
You should be using the array method `push`.
|
||||
Você deve usar o método de array `push`.
|
||||
|
||||
```js
|
||||
assert(code.match(/myArray.push/));
|
||||
```
|
||||
|
||||
`myArray` should equal `[9,7,5,3,1]`.
|
||||
`myArray` deve ser igual a `[9,7,5,3,1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(myArray, [9, 7, 5, 3, 1]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 565bbe00e9cc8ac0725390f4
|
||||
title: Counting Cards
|
||||
title: Contando cartas
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c6KE7ty'
|
||||
forumTopicId: 16809
|
||||
@ -9,24 +9,23 @@ dashedName: counting-cards
|
||||
|
||||
# --description--
|
||||
|
||||
In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called [Card Counting](https://en.wikipedia.org/wiki/Card_counting).
|
||||
No jogo de casino Blackjack, um jogador pode ganhar vantagem sobre a casa, mantendo o número relativo de cartas altas e baixas restantes no deck. Isso se chama [Contagem de Cartas](https://en.wikipedia.org/wiki/Card_counting).
|
||||
|
||||
Having more high cards remaining in the deck favors the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.
|
||||
Ter cartas mais altas restantes no deck favorece o jogador. A cada carta é atribuído um valor de acordo com a tabela abaixo. Quando o contador for positivo, o jogador deve apostar alto. Quando a contagem for zero ou negativa, o jogador deverá apostar baixo.
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Count Change</th><th>Cards</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K', 'A'</td></tr></tbody></table>
|
||||
<table class='table table-striped'><thead><tr><th>Contagem de mudança</th><th>Cartas</th></tr></thead><tbody><tr><td>+1</td><td>2, 3, 4, 5, 6</td></tr><tr><td>0</td><td>7, 8, 9</td></tr><tr><td>-1</td><td>10, 'J', 'Q', 'K', 'A'</td></tr></tbody></table>
|
||||
|
||||
You will write a card counting function. It will receive a `card` parameter, which can be a number or a string, and increment or decrement the global `count` variable according to the card's value (see table). The function will then return a string with the current count and the string `Bet` if the count is positive, or `Hold` if the count is zero or negative. The current count and the player's decision (`Bet` or `Hold`) should be separated by a single space.
|
||||
Você vai escrever uma função de contagem de cartas. A função receberá um parâmetro `card`, a qual pode ser um número ou uma string e incrementar ou decrementar a variável global `count` de acordo com o valor da carta (veja a tabela). Em seguida, a função retornará a string com o valor atual de contagem (variável count) e a string `Bet` se a contagem for positiva, ou `Hold` se a contagem for zero ou negativa. A contagem atual e a decisão do jogador (`Bet` ou `Hold`) deve ser separado por um único espaço.
|
||||
|
||||
**Example Outputs:** `-3 Hold` or `5 Bet`
|
||||
**Exemplo de Saída:** `-3 Hold` ou `5 Bet`
|
||||
|
||||
**Hint**
|
||||
Do NOT reset `count` to 0 when value is 7, 8, or 9.
|
||||
Do NOT return an array.
|
||||
Do NOT include quotes (single or double) in the output.
|
||||
**Dica**
|
||||
Não redefina o valor de `count` para 0 quando o valor for 7, 8, or 9. Não retorne um array.
|
||||
Não inclua aspas (simples ou duplas) na saída.
|
||||
|
||||
# --hints--
|
||||
|
||||
Cards Sequence 2, 3, 4, 5, 6 should return `5 Bet`
|
||||
Sequências de cartas 2, 3, 4, 5, 6 deve retornar `5 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -45,7 +44,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 7, 8, 9 should return the string `0 Hold`
|
||||
Sequência de cartas 7, 8, 9 deve retornar a string `0 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -62,7 +61,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 10, J, Q, K, A should return the string `-5 Hold`
|
||||
Sequência de cartas 10, J, Q, K, A deve retornar a string `-5 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -81,7 +80,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 3, 7, Q, 8, A should return the string `-1 Hold`
|
||||
Sequência de cartas 3, 7, Q, 8, A deve retornar a string `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -100,7 +99,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 2, J, 9, 2, 7 should return the string `1 Bet`
|
||||
Sequência de cartas 2, J, 9, 2, 7 deve retornar a string `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -119,7 +118,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 2, 2, 10 should return the string `1 Bet`
|
||||
Sequência de cartas 2, 2, 10 deve retornar a string `1 Bet`
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -136,7 +135,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cards Sequence 3, 2, A, 10, K should return the string `-1 Hold`
|
||||
Sequência de cartas 3, 2, A, 10, K deve retornar a string `-1 Hold`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1391c1c11feddfaeb4bdef
|
||||
title: Create Decimal Numbers with JavaScript
|
||||
title: Crie Números Decimais com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/ca8GEuW'
|
||||
forumTopicId: 16826
|
||||
@ -9,23 +9,23 @@ dashedName: create-decimal-numbers-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
We can store decimal numbers in variables too. Decimal numbers are sometimes referred to as <dfn>floating point</dfn> numbers or <dfn>floats</dfn>.
|
||||
Nós também podemos armazenar números decimais em variáveis. Números decimais são referidos as vezes como números de <dfn>ponto flutuante</dfn> ou <dfn>floats</dfn>.
|
||||
|
||||
**Note:** Not all real numbers can accurately be represented in <dfn>floating point</dfn>. This can lead to rounding errors. [Details Here](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
|
||||
**Nota:** Nem todos os números reais podem ser representados com precisão no <dfn>ponto flutuante</dfn>. Isso pode levar a erros de arredondamento. [Detalhes aqui](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a variable `myDecimal` and give it a decimal value with a fractional part (e.g. `5.7`).
|
||||
Crie a variável `myDecimal` e dê a ela um valor decimal com uma parte fracional (e.g. `5.7`).
|
||||
|
||||
# --hints--
|
||||
|
||||
`myDecimal` should be a number.
|
||||
`myDecimal` deve ser um número.
|
||||
|
||||
```js
|
||||
assert(typeof myDecimal === 'number');
|
||||
```
|
||||
|
||||
`myDecimal` should have a decimal point
|
||||
`myDecimal` deve ter um ponto decimal
|
||||
|
||||
```js
|
||||
assert(myDecimal % 1 != 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c443eddfaeb5bdef
|
||||
title: Declare JavaScript Variables
|
||||
title: Declare Variáveis JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cNanrHq'
|
||||
forumTopicId: 17556
|
||||
@ -9,32 +9,32 @@ dashedName: declare-javascript-variables
|
||||
|
||||
# --description--
|
||||
|
||||
In computer science, <dfn>data</dfn> is anything that is meaningful to the computer. JavaScript provides eight different <dfn>data types</dfn> which are `undefined`, `null`, `boolean`, `string`, `symbol`, `bigint`, `number`, and `object`.
|
||||
Na ciência da computação, <dfn>dado</dfn> é qualquer coisa que tenha significado ao computador. JavaScript fornece oito <dfn>tipos de dados</dfn> diferentes que são `undefined`, `null`, `boolean`, `string`, `symbol`, `bigint`, `number` e `object`.
|
||||
|
||||
For example, computers distinguish between numbers, such as the number `12`, and `strings`, such as `"12"`, `"dog"`, or `"123 cats"`, which are collections of characters. Computers can perform mathematical operations on a number, but not on a string.
|
||||
Por exemplo, os computadores distinguem números, como o número`12`, e`strings`, como o `"12"`, `"dog"`, ou`"123 cats"`, as quais são coleções de caracteres. Computadores podem realizar operações matemáticas em um número, mas não em string.
|
||||
|
||||
<dfn>Variables</dfn> allow computers to store and manipulate data in a dynamic fashion. They do this by using a "label" to point to the data rather than using the data itself. Any of the eight data types may be stored in a variable.
|
||||
<dfn>Variáveis</dfn> permitem aos computadores armazenar e manipular dados de forma dinâmica. Eles fazem isso usando um "rótulo" para apontar ao dado ao invés de usar o próprio dado. Qualquer uma dos 8 tipos de dados podem ser armazenados em variável.
|
||||
|
||||
Variables are similar to the x and y variables you use in mathematics, which means they're a simple name to represent the data we want to refer to. Computer variables differ from mathematical variables in that they can store different values at different times.
|
||||
Variáveis são similares às variáveis x e y utilizados na matemática, o que significa que elas são simples nomes para representar os dados que eles querem se referir. Variáveis de computador diferem das variáveis matemáticas porque elas podem armazenar diferentes valores em momentos diferentes.
|
||||
|
||||
We tell JavaScript to create or <dfn>declare</dfn> a variable by putting the keyword `var` in front of it, like so:
|
||||
Dizemos ao JavaScript para criar ou declarar uma variável colocando a palavra-chave `var` na frente dela, dessa forma:
|
||||
|
||||
```js
|
||||
var ourName;
|
||||
```
|
||||
|
||||
creates a variable called `ourName`. In JavaScript we end statements with semicolons. Variable names can be made up of numbers, letters, and `$` or `_`, but may not contain spaces or start with a number.
|
||||
cria uma variável chamada `ourName`. Em JavaScript terminamos uma instrução com ponto e vírgula. Nomes de variáveis podem ser formadas por números, letras e `$` ou `_`, mas não pode conter espaços ou começar com um número.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `var` keyword to create a variable called `myName`.
|
||||
Use a palavra-chave `var` para criar uma variável chamada `myName`.
|
||||
|
||||
**Hint**
|
||||
Look at the `ourName` example above if you get stuck.
|
||||
**Dica**
|
||||
Olhe o exemplo acima de `ourName` se você ficar travado.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should declare `myName` with the `var` keyword, ending with a semicolon
|
||||
Você deve declarar `myName` com a palavra-chave `var`, terminando com ponto e vírgula
|
||||
|
||||
```js
|
||||
assert(/var\s+myName\s*;/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c444eddfaeb5bdef
|
||||
title: Declare String Variables
|
||||
title: Declarar Variáveis de String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvWU6'
|
||||
forumTopicId: 17557
|
||||
@ -9,21 +9,21 @@ dashedName: declare-string-variables
|
||||
|
||||
# --description--
|
||||
|
||||
Previously we have used the code
|
||||
Anteriormente nós usamos o código
|
||||
|
||||
```js
|
||||
var myName = "your name";
|
||||
```
|
||||
|
||||
`"your name"` is called a <dfn>string</dfn> <dfn>literal</dfn>. It is a string because it is a series of zero or more characters enclosed in single or double quotes.
|
||||
`"your name"` é chamado de <dfn>string literal</dfn>. É uma string porque é uma série de 0 ou mais caracteres entre aspas simples ou duplas.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create two new string variables: `myFirstName` and `myLastName` and assign them the values of your first and last name, respectively.
|
||||
Crie duas novas variáveis de string: `myFirstName` e `myLastName` e atribua a eles os valores do seu primeiro e último nome, respectivamente.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myFirstName` should be a string with at least one character in it.
|
||||
`myFirstName` deve ser uma string com pelo menos um caractere.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,7 +41,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`myLastName` should be a string with at least one character in it.
|
||||
`myLastName` deve ser uma string com pelo menos um caractere.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ad
|
||||
title: Decrement a Number with JavaScript
|
||||
title: Decremente um Número com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cM2KeS2'
|
||||
forumTopicId: 17558
|
||||
@ -9,33 +9,33 @@ dashedName: decrement-a-number-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
You can easily <dfn>decrement</dfn> or decrease a variable by one with the `--` operator.
|
||||
Você pode facilmente <dfn>decrementar</dfn> ou diminuir uma variável por um com o operador `--`.
|
||||
|
||||
```js
|
||||
i--;
|
||||
```
|
||||
|
||||
is the equivalent of
|
||||
é o equivalente a
|
||||
|
||||
```js
|
||||
i = i - 1;
|
||||
```
|
||||
|
||||
**Note:** The entire line becomes `i--;`, eliminating the need for the equal sign.
|
||||
**Nota:** A linha inteira torna-se `i--;`, eliminando a necessidade para o sinal de igual (atribuição).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the code to use the `--` operator on `myVar`.
|
||||
Altere o código para usar o operador `--` na variável `myVar`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myVar` should equal `10`.
|
||||
`myVar` deve ser igual a `10`.
|
||||
|
||||
```js
|
||||
assert(myVar === 10);
|
||||
```
|
||||
|
||||
`myVar = myVar - 1;` should be changed.
|
||||
`myVar = myVar - 1;` deve ser alterado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -43,13 +43,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use the `--` operator on `myVar`.
|
||||
Você deve usar o operador `--` na variável `myVar`.
|
||||
|
||||
```js
|
||||
assert(/[-]{2}\s*myVar|myVar\s*[-]{2}/.test(code));
|
||||
```
|
||||
|
||||
You should not change code above the specified comment.
|
||||
Você não deve alterar o código acima do comentário especificado.
|
||||
|
||||
```js
|
||||
assert(/var myVar = 11;/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56bbb991ad1ed5201cd392d3
|
||||
title: Delete Properties from a JavaScript Object
|
||||
title: Excluir Propriedades de um Objeto JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cDqKdTv'
|
||||
forumTopicId: 17560
|
||||
@ -9,13 +9,13 @@ dashedName: delete-properties-from-a-javascript-object
|
||||
|
||||
# --description--
|
||||
|
||||
We can also delete properties from objects like this:
|
||||
Podemos também excluir propriedades de objetos dessa forma:
|
||||
|
||||
```js
|
||||
delete ourDog.bark;
|
||||
```
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
```js
|
||||
var ourDog = {
|
||||
@ -29,7 +29,7 @@ var ourDog = {
|
||||
delete ourDog.bark;
|
||||
```
|
||||
|
||||
After the last line shown above, `ourDog` looks like:
|
||||
Após a última linha mostrada acima, `ourDog` se parece com:
|
||||
|
||||
```js
|
||||
{
|
||||
@ -42,17 +42,17 @@ After the last line shown above, `ourDog` looks like:
|
||||
|
||||
# --instructions--
|
||||
|
||||
Delete the `tails` property from `myDog`. You may use either dot or bracket notation.
|
||||
Exclua a propriedade `tails` de `myDog`. Você pode usar tanto notação de ponto quanto notação de colchetes.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should delete the property `tails` from `myDog`.
|
||||
Você deve excluir a propriedade `tails` de `myDog`.
|
||||
|
||||
```js
|
||||
assert(typeof myDog === 'object' && myDog.tails === undefined);
|
||||
```
|
||||
|
||||
You should not modify the `myDog` setup.
|
||||
Você não deve modificar a configuração de `myDog`.
|
||||
|
||||
```js
|
||||
assert(code.match(/"tails": 1/g).length > 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7993c9ca9feddfaeb7bdef
|
||||
title: Divide One Decimal by Another with JavaScript
|
||||
title: Divida Um Decimal por Outro com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cBZe9AW'
|
||||
forumTopicId: 18255
|
||||
@ -9,27 +9,27 @@ dashedName: divide-one-decimal-by-another-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
Now let's divide one decimal by another.
|
||||
Agora vamos dividir um decimal por outro.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change the `0.0` so that `quotient` will equal to `2.2`.
|
||||
Modifique `0.0` para que a variável `quotient` seja igual a `2.2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `quotient` should equal `2.2`
|
||||
A variável `quotient` deve ser igual a `2.2`
|
||||
|
||||
```js
|
||||
assert(quotient === 2.2);
|
||||
```
|
||||
|
||||
You should use the `/` operator to divide 4.4 by 2
|
||||
Você deve usar o operador `/` para dividir 4.4 por 2
|
||||
|
||||
```js
|
||||
assert(/4\.40*\s*\/\s*2\.*0*/.test(code));
|
||||
```
|
||||
|
||||
The quotient variable should only be assigned once
|
||||
A variável quotient deve ser atribuída apenas uma vez
|
||||
|
||||
```js
|
||||
assert(code.match(/quotient/g).length === 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb6bdef
|
||||
title: Divide One Number by Another with JavaScript
|
||||
title: Divida Um Número por Outro com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cqkbdAr'
|
||||
forumTopicId: 17566
|
||||
@ -9,30 +9,30 @@ dashedName: divide-one-number-by-another-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
We can also divide one number by another.
|
||||
Nós também podemos dividir um número por outro.
|
||||
|
||||
JavaScript uses the `/` symbol for division.
|
||||
JavaScript usa o símbolo `/` para divisão.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
```js
|
||||
myVar = 16 / 2;
|
||||
```
|
||||
|
||||
`myVar` now has the value `8`.
|
||||
`myVar` agora possui o valor `8`.
|
||||
# --instructions--
|
||||
|
||||
Change the `0` so that the `quotient` is equal to `2`.
|
||||
Altere `0` para que a variável `quotient` seja igual a `2`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `quotient` should be equal to 2.
|
||||
A variável `quotient` deve ser igual a 2.
|
||||
|
||||
```js
|
||||
assert(quotient === 2);
|
||||
```
|
||||
|
||||
You should use the `/` operator.
|
||||
Você deve usar o operador `/`.
|
||||
|
||||
```js
|
||||
assert(/\d+\s*\/\s*\d+/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b6
|
||||
title: Escape Sequences in Strings
|
||||
title: Escape Sequências em Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqRh6'
|
||||
forumTopicId: 17567
|
||||
@ -9,36 +9,36 @@ dashedName: escape-sequences-in-strings
|
||||
|
||||
# --description--
|
||||
|
||||
Quotes are not the only characters that can be <dfn>escaped</dfn> inside a string. There are two reasons to use escaping characters:
|
||||
Aspas não são os únicos caracteres que podem ser <dfn>escapadas</dfn> dentro de uma string. Há dois motivos para usar caracteres de escapamento:
|
||||
|
||||
1. To allow you to use characters you may not otherwise be able to type out, such as a carriage return.
|
||||
2. To allow you to represent multiple quotes in a string without JavaScript misinterpreting what you mean.
|
||||
1. Para permitir que você use caracteres, você pode não ser capaz de digitar caso contrário, como um retorno de carro.
|
||||
2. Para permiti-lo representar várias aspas em uma string sem o JavaScript entender erroneamente o que você quis dizer.
|
||||
|
||||
We learned this in the previous challenge.
|
||||
Aprendemos isso no desafio anterior.
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Code</th><th>Output</th></tr></thead><tbody><tr><td><code>\'</code></td><td>single quote</td></tr><tr><td><code>\"</code></td><td>double quote</td></tr><tr><td><code>\\</code></td><td>backslash</td></tr><tr><td><code>\n</code></td><td>newline</td></tr><tr><td><code>\r</code></td><td>carriage return</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\b</code></td><td>word boundary</td></tr><tr><td><code>\f</code></td><td>form feed</td></tr></tbody></table>
|
||||
<table class='table table-striped'><thead><tr><th>Código</th><th>Saída</th></tr></thead><tbody><tr><td><code>\'</code></td><td>aspas simples</td></tr><tr><td><code>\"</code></td><td>aspas duplas</td></tr><tr><td><code>\\</code></td><td>barra invertida</td></tr><tr><td><code>\n</code></td><td>nova linha</td></tr><tr><td><code>\r</code></td><td>retorno de carro</td></tr><tr><td><code>\t</code></td><td>tab</td></tr><tr><td><code>\b</code></td><td>limite de palavra</td></tr><tr><td><code>\f</code></td><td>quebra de página</td></tr></tbody></table>
|
||||
|
||||
*Note that the backslash itself must be escaped in order to display as a backslash.*
|
||||
*Note que a própria barra invertida deve ser escapada para ser exibida como uma barra invertida.*
|
||||
|
||||
# --instructions--
|
||||
|
||||
Assign the following three lines of text into the single variable `myStr` using escape sequences.
|
||||
Atribua as três linhas de texto a seguir em uma única variável `myStr` usando sequências de escapamento.
|
||||
|
||||
<blockquote>FirstLine<br> \SecondLine<br>ThirdLine</blockquote>
|
||||
|
||||
You will need to use escape sequences to insert special characters correctly. You will also need to follow the spacing as it looks above, with no spaces between escape sequences or words.
|
||||
Você precisará usar sequências de escapamento para inserir corretamente os caracteres especiais. Você também precisará seguir os espaçamentos assim como se parece acima, sem espaços entre sequências de escapamento ou palavras.
|
||||
|
||||
**Note:** The indentation for `SecondLine` is achieved with the tab escape character, not spaces.
|
||||
**Nota:** A identação para `SecondLine` é alcançada com o caracter de espaçamento tab, e não espaços.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myStr` should not contain any spaces
|
||||
`myStr` não deve conter espaços
|
||||
|
||||
```js
|
||||
assert(!/ /.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` should contain the strings `FirstLine`, `SecondLine` and `ThirdLine` (remember case sensitivity)
|
||||
`myStr` deve conter as strings `FirstLine`, `SecondLine` e `ThirdLine` (lembre-se da sensibilidade de maiúsculas e minúsculas 'case sensitivity')
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -46,31 +46,31 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`FirstLine` should be followed by the newline character `\n`
|
||||
`FirstLine` deve ser seguido pelo caractere de nova linha `\n`
|
||||
|
||||
```js
|
||||
assert(/FirstLine\n/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` should contain a tab character `\t` which follows a newline character
|
||||
`myStr` deve conter o caracter tab `\t` a qual está logo após o caractere de nova linha `\n`
|
||||
|
||||
```js
|
||||
assert(/\n\t/.test(myStr));
|
||||
```
|
||||
|
||||
`SecondLine` should be preceded by the backslash character `\`
|
||||
`SecondLine` deve ser precedida pelo caractere de barra invertida `\`
|
||||
|
||||
```js
|
||||
assert(/\\SecondLine/.test(myStr));
|
||||
```
|
||||
|
||||
There should be a newline character between `SecondLine` and `ThirdLine`
|
||||
Deve ter um caractere de nova linha entre `SecondLine` e `ThirdLine`
|
||||
|
||||
```js
|
||||
assert(/SecondLine\nThirdLine/.test(myStr));
|
||||
```
|
||||
|
||||
`myStr` should only contain characters shown in the instructions
|
||||
`myStr` deve conter apenas caracteres mostrados nas instruções
|
||||
|
||||
```js
|
||||
assert(myStr === 'FirstLine\n\t\\SecondLine\nThirdLine');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244b5
|
||||
title: Escaping Literal Quotes in Strings
|
||||
title: Escapando Aspas Literais em Strings
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QvgSr'
|
||||
forumTopicId: 17568
|
||||
@ -9,15 +9,15 @@ dashedName: escaping-literal-quotes-in-strings
|
||||
|
||||
# --description--
|
||||
|
||||
When you are defining a string you must start and end with a single or double quote. What happens when you need a literal quote: `"` or `'` inside of your string?
|
||||
Quando você estiver definindo uma sequência de caracteres você deve iniciar e terminar com uma aspa simples ou dupla. O que acontece quando você precisa de uma cotação literal: `"` ou `'` dentro de sua string?
|
||||
|
||||
In JavaScript, you can <dfn>escape</dfn> a quote from considering it as an end of string quote by placing a <dfn>backslash</dfn> (`\`) in front of the quote.
|
||||
Em JavaScript, você pode <dfn>escapar</dfn> uma aspas para não ser considerada como o fim de uma string ao colocar a <dfn>barra invertida</dfn> (`\`) na frente da aspa.
|
||||
|
||||
```js
|
||||
var sampleStr = "Alan said, \"Peter is learning JavaScript\".";
|
||||
```
|
||||
|
||||
This signals to JavaScript that the following quote is not the end of the string, but should instead appear inside the string. So if you were to print this to the console, you would get:
|
||||
Isso sinaliza ao JavaScript que a seguinte aspa não é o fim de uma string, mas ao invés disso, deve aparecer dentro da string. Então, se você fosse imprimir isso no console, você obteria:
|
||||
|
||||
```js
|
||||
Alan said, "Peter is learning JavaScript".
|
||||
@ -25,7 +25,7 @@ Alan said, "Peter is learning JavaScript".
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use <dfn>backslashes</dfn> to assign a string to the `myStr` variable so that if you were to print it to the console, you would see:
|
||||
Use <dfn>barras invertidas</dfn> para atribuir a string à variável `myStr` para que se você fosse imprimi-la no console, você veria:
|
||||
|
||||
```js
|
||||
I am a "double quoted" string inside "double quotes".
|
||||
@ -33,13 +33,13 @@ I am a "double quoted" string inside "double quotes".
|
||||
|
||||
# --hints--
|
||||
|
||||
You should use two double quotes (`"`) and four escaped double quotes (`\"`).
|
||||
Você deve usar aspas duplas (`"`) e quatro aspas duplas escapadas (`\"`).
|
||||
|
||||
```js
|
||||
assert(code.match(/\\"/g).length === 4 && code.match(/[^\\]"/g).length === 2);
|
||||
```
|
||||
|
||||
Variable myStr should contain the string: `I am a "double quoted" string inside "double quotes".`
|
||||
Variável myStr deve conter a string: `I am a "double quoted" string inside "double quotes".`
|
||||
|
||||
```js
|
||||
assert(/I am a "double quoted" string inside "double quotes(\."|"\.)$/.test(myStr));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bd7123c9c448eddfaeb5bdef
|
||||
title: Find the Length of a String
|
||||
title: Encontre o Tamanho de uma String
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cvmqEAd'
|
||||
forumTopicId: 18182
|
||||
@ -9,23 +9,23 @@ dashedName: find-the-length-of-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
You can find the length of a `String` value by writing `.length` after the string variable or string literal.
|
||||
Você pode encontrar o tamanho de um valor de `String` ao escrever `.length` após a variável de string ou literal de string.
|
||||
|
||||
```js
|
||||
console.log("Alan Peter".length);
|
||||
```
|
||||
|
||||
The value `10` would be displayed in the console.
|
||||
O valor `10` seria exibido no console.
|
||||
|
||||
For example, if we created a variable `var firstName = "Ada"`, we could find out how long the string `Ada` is by using the `firstName.length` property.
|
||||
Por exemplo, se nós criarmos uma variável `var firstName = "Ada"`, poderíamos descobrir qual o tamanho da string `Ada` ao usar a propriedade `firstName.length`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use the `.length` property to count the number of characters in the `lastName` variable and assign it to `lastNameLength`.
|
||||
Use a propriedade `.length` para contar o número de caracteres na variável `lastName` e atribui-la a `lastNameLength`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change the variable declarations in the `// Setup` section.
|
||||
Você não deve alterar as declarações de variáveis a seção `// Setup`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -34,13 +34,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`lastNameLength` should be equal to eight.
|
||||
`lastNameLength` deve ser igual a oito.
|
||||
|
||||
```js
|
||||
assert(typeof lastNameLength !== 'undefined' && lastNameLength === 8);
|
||||
```
|
||||
|
||||
You should be getting the length of `lastName` by using `.length` like this: `lastName.length`.
|
||||
Você deve estar recebendo o tamanho de `lastName` ao usar `.length` dessa forma: `lastName.length`.
|
||||
|
||||
```js
|
||||
assert(code.match(/=\s*lastName\.length/g) && !code.match(/lastName\s*=\s*8/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244ae
|
||||
title: Finding a Remainder in JavaScript
|
||||
title: Descobrindo o Resto em JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cWP24Ub'
|
||||
forumTopicId: 18184
|
||||
@ -9,38 +9,38 @@ dashedName: finding-a-remainder-in-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
The <dfn>remainder</dfn> operator `%` gives the remainder of the division of two numbers.
|
||||
O operador de <dfn>resto</dfn> `%` retorna o resto da divisão de dois números.
|
||||
|
||||
**Example**
|
||||
**Exemplo**
|
||||
|
||||
<blockquote>5 % 2 = 1 because<br>Math.floor(5 / 2) = 2 (Quotient)<br>2 * 2 = 4<br>5 - 4 = 1 (Remainder)</blockquote>
|
||||
<blockquote>5 % 2 = 1 porque<br>Math.floor(5 / 2) = 2 (Quociente)<br> 2 * 2 = 4<br>5 - 4 = 1 (Resto)</blockquote>
|
||||
|
||||
**Usage**
|
||||
In mathematics, a number can be checked to be even or odd by checking the remainder of the division of the number by `2`.
|
||||
**Uso**
|
||||
Na matemática, um número pode ser verificado para ser par ou ímpar ao verificar o resto da divisão de um número por `2`.
|
||||
|
||||
<blockquote>17 % 2 = 1 (17 is Odd)<br>48 % 2 = 0 (48 is Even)</blockquote>
|
||||
<blockquote>17 % 2 = 1 (17 é Ímpar)<br>48 % 2 = 0 (48 é Par)</blockquote>
|
||||
|
||||
**Note:** The <dfn>remainder</dfn> operator is sometimes incorrectly referred to as the modulus operator. It is very similar to modulus, but does not work properly with negative numbers.
|
||||
**Nota:** O operador de <dfn>resto</dfn> às vezes é referido incorretamente como o operador de módulo. É muito semelhante ao módulo, mas não funciona adequadamente com números negativos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Set `remainder` equal to the remainder of `11` divided by `3` using the <dfn>remainder</dfn> (`%`) operator.
|
||||
Define o `resto` igual ao restante de `11` dividido por `3` usando o operador de <dfn>restante</dfn> (`%`).
|
||||
|
||||
# --hints--
|
||||
|
||||
The variable `remainder` should be initialized
|
||||
A variável `remainder` deve ser inicializada
|
||||
|
||||
```js
|
||||
assert(/var\s+?remainder/.test(code));
|
||||
```
|
||||
|
||||
The value of `remainder` should be `2`
|
||||
O valor de `remainder` deve ser `2`
|
||||
|
||||
```js
|
||||
assert(remainder === 2);
|
||||
```
|
||||
|
||||
You should use the `%` operator
|
||||
Você deve usar o operador `%`
|
||||
|
||||
```js
|
||||
assert(/\s+?remainder\s*?=\s*?.*%.*;?/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c11feddfaeb9bdef
|
||||
title: Generate Random Fractions with JavaScript
|
||||
title: Gerar Frações Aleatórias com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cyWJJs3'
|
||||
forumTopicId: 18185
|
||||
@ -9,31 +9,31 @@ dashedName: generate-random-fractions-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
Random numbers are useful for creating random behavior.
|
||||
Números aleatórios são úteis para criar comportamento aleatório.
|
||||
|
||||
JavaScript has a `Math.random()` function that generates a random decimal number between `0` (inclusive) and `1` (exclusive). Thus `Math.random()` can return a `0` but never return a `1`.
|
||||
JavaScript tem a função `Math.random()` que gera um número decimal aleatório entre `0` (incluso) e `1` (excluso). Assim, `Math.random()` pode retornar um `0` mas nunca retornará `1`.
|
||||
|
||||
**Note:** Like [Storing Values with the Assignment Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), all function calls will be resolved before the `return` executes, so we can `return` the value of the `Math.random()` function.
|
||||
**Nota:** Como [Armazenar Valores com Operador de Atribuição](/learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator), todas as chamadas de funções serão resolvidas antes de executar o `return`, para que possamos `returnar` o valor da função de `Math.random()`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Change `randomFraction` to return a random number instead of returning `0`.
|
||||
Altere `randomFraction` para retornar um número aleatório ao invés de retornar `0`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`randomFraction` should return a random number.
|
||||
`randomFraction` deve retornar um número aleatório.
|
||||
|
||||
```js
|
||||
assert(typeof randomFraction() === 'number');
|
||||
```
|
||||
|
||||
The number returned by `randomFraction` should be a decimal.
|
||||
O número retornado por `randomFraction` deve ser um decimal.
|
||||
|
||||
```js
|
||||
assert((randomFraction() + '').match(/\./g));
|
||||
```
|
||||
|
||||
You should be using `Math.random` to generate the random decimal number.
|
||||
Você deve estar usando `Math.random` para gerar o número decimal aleatório.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math\.random/g).length >= 0);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb1bdef
|
||||
title: Generate Random Whole Numbers with JavaScript
|
||||
title: Gerar Números Inteiros Aleatórios com JavaScript
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cRn6bfr'
|
||||
forumTopicId: 18186
|
||||
@ -9,27 +9,27 @@ dashedName: generate-random-whole-numbers-with-javascript
|
||||
|
||||
# --description--
|
||||
|
||||
It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.
|
||||
É ótimo podermos gerar números decimais aleatórios, mas é ainda mais útil se usarmos para gerar números inteiros aleatórios.
|
||||
|
||||
<ol><li>Use <code>Math.random()</code> to generate a random decimal.</li><li>Multiply that random decimal by <code>20</code>.</li><li>Use another function, <code>Math.floor()</code> to round the number down to its nearest whole number.</li></ol>
|
||||
<ol><li>Use <code>Math.random()</code> para gerar um decimal aleatório.</li><li>Multiplique o decimal aleatório por <code>20</code>.</li><li>Use outra função, <code>Math.floor()</code> para arredondar o número para baixo para o número inteiro mais próximo.</li></ol>
|
||||
|
||||
Remember that `Math.random()` can never quite return a `1` and, because we're rounding down, it's impossible to actually get `20`. This technique will give us a whole number between `0` and `19`.
|
||||
Lembre-se que `Math.random()` pode nunca retornar um `1` e, porque nós estamos arredondando, é impossível receber examente `20`. Essa técnica nos dará um número inteiro entre `0` e `19`.
|
||||
|
||||
Putting everything together, this is what our code looks like:
|
||||
Juntando tudo, é assim que nosso código se parece:
|
||||
|
||||
```js
|
||||
Math.floor(Math.random() * 20);
|
||||
```
|
||||
|
||||
We are calling `Math.random()`, multiplying the result by 20, then passing the value to `Math.floor()` function to round the value down to the nearest whole number.
|
||||
Nós estamos chamando `Math.random()`, multiplicando o resultado por 20, e em seguida passando o valor para a função `Math.floor()` para arredondar o valor para o número inteiro para baixo mais próximo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use this technique to generate and return a random whole number between `0` and `9`.
|
||||
Use essa técnica para gerar e retornar um número inteiro aleatório entre `0` e `9`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The result of `randomWholeNum` should be a whole number.
|
||||
O resultado de `randomWholeNum` deve ser um número inteiro.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -41,13 +41,13 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use `Math.random` to generate a random number.
|
||||
Você deve usar `Math.random` para gerar um número aleatório.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.random/g).length >= 1);
|
||||
```
|
||||
|
||||
You should have multiplied the result of `Math.random` by 10 to make it a number that is between zero and nine.
|
||||
Você deve ter multiplicado o resultado de `Math.random` por 10 para torná-lo um número que está entre zero e nove.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -56,7 +56,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use `Math.floor` to remove the decimal part of the number.
|
||||
Você deve usar `Math.floor` para remover a parte decimal do número.
|
||||
|
||||
```js
|
||||
assert(code.match(/Math.floor/g).length >= 1);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: cf1111c1c12feddfaeb2bdef
|
||||
title: Generate Random Whole Numbers within a Range
|
||||
title: Gere Números Inteiros Aleatórios dentro de um Intervalo
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cm83yu6'
|
||||
forumTopicId: 18187
|
||||
@ -9,11 +9,11 @@ dashedName: generate-random-whole-numbers-within-a-range
|
||||
|
||||
# --description--
|
||||
|
||||
Instead of generating a random whole number between zero and a given number like we did before, we can generate a random whole number that falls within a range of two specific numbers.
|
||||
Ao invés de gerar um número inteiro aleatório entre 0 e um número especificado como fizemos anteriormente, nós podemos gerar um número inteiro aleatório que cai entre um intervalo de dois números especificados.
|
||||
|
||||
To do this, we'll define a minimum number `min` and a maximum number `max`.
|
||||
Para isso, definiremos um número mínimo `min` e um número máximo`max`.
|
||||
|
||||
Here's the formula we'll use. Take a moment to read it and try to understand what this code is doing:
|
||||
Aqui está a fórmula que usaremos. Leve um momento para ler e entender o que esse código está fazendo:
|
||||
|
||||
```js
|
||||
Math.floor(Math.random() * (max - min + 1)) + min
|
||||
@ -21,29 +21,29 @@ Math.floor(Math.random() * (max - min + 1)) + min
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function called `randomRange` that takes a range `myMin` and `myMax` and returns a random whole number that's greater than or equal to `myMin`, and is less than or equal to `myMax`, inclusive.
|
||||
Crie uma função chamada `randomRange` que recebe um intervalo de `myMin` e `myMax` e retorne um número inteiro aleatório que é maior ou igual a `myMin`, e é menor ou igual a `myMax`, inclusivo.
|
||||
|
||||
# --hints--
|
||||
|
||||
The lowest random number that can be generated by `randomRange` should be equal to your minimum number, `myMin`.
|
||||
O menor número aleatório que poderá ser gerado por `randomRange` deve ser igual ao seu número mínimo, `myMin`.
|
||||
|
||||
```js
|
||||
assert(calcMin === 5);
|
||||
```
|
||||
|
||||
The highest random number that can be generated by `randomRange` should be equal to your maximum number, `myMax`.
|
||||
O maior número aleatório que poderá ser gerado por `randomRange` deve ser igual ao seu número máximo, `myMax`.
|
||||
|
||||
```js
|
||||
assert(calcMax === 15);
|
||||
```
|
||||
|
||||
The random number generated by `randomRange` should be an integer, not a decimal.
|
||||
O número aleatório gerado por `randomRange` deve ser um inteiro, não um decimal.
|
||||
|
||||
```js
|
||||
assert(randomRange(0, 1) % 1 === 0);
|
||||
```
|
||||
|
||||
`randomRange` should use both `myMax` and `myMin`, and return a random number in your range.
|
||||
`randomRange` deve usar ambos `myMax` e `myMin` e retornar um número aleatório no seu intervalo.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244be
|
||||
title: Global Scope and Functions
|
||||
title: Escopo Global e Funções
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/cQM7mCN'
|
||||
forumTopicId: 18193
|
||||
@ -9,37 +9,37 @@ dashedName: global-scope-and-functions
|
||||
|
||||
# --description--
|
||||
|
||||
In JavaScript, <dfn>scope</dfn> refers to the visibility of variables. Variables which are defined outside of a function block have <dfn>Global</dfn> scope. This means, they can be seen everywhere in your JavaScript code.
|
||||
Em JavaScript, <dfn>escopo</dfn> refere-se à visibilidade de variáveis. Variáveis que são definidas fora de um bloco de função tem o escopo <dfn>Global</dfn>. Isso significa, que elas podem ser vistas em qualquer lugar no seu código JavaScript.
|
||||
|
||||
Variables which are declared without the `var` keyword are automatically created in the `global` scope. This can create unintended consequences elsewhere in your code or when running a function again. You should always declare your variables with `var`.
|
||||
Variáveis que são declaradas sem a palavra-chave `var` são automaticamente criadas no escopo `global`. Isso pode criar consequências indesejadas em outro lugar no seu código ou quando executando uma função novamente. Você sempre deve declarar suas variáveis com `var`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using `var`, declare a global variable named `myGlobal` outside of any function. Initialize it with a value of `10`.
|
||||
Usando `var`, declare uma variável global chamada `myGlobal` fora de qualquer função. Inicialize ela com o valor de `10`.
|
||||
|
||||
Inside function `fun1`, assign `5` to `oopsGlobal` ***without*** using the `var` keyword.
|
||||
Dentro da função `fun1`, atribua `5` para `oopsGlobal` ***sem*** usar a palavra-chave `var`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`myGlobal` should be defined
|
||||
`myGlobal` deve ser definido
|
||||
|
||||
```js
|
||||
assert(typeof myGlobal != 'undefined');
|
||||
```
|
||||
|
||||
`myGlobal` should have a value of `10`
|
||||
`myGlobal` deve ter o valor de `10`
|
||||
|
||||
```js
|
||||
assert(myGlobal === 10);
|
||||
```
|
||||
|
||||
`myGlobal` should be declared using the `var` keyword
|
||||
`myGlobal` deve ser declarada usando a palavra-chave `var`
|
||||
|
||||
```js
|
||||
assert(/var\s+myGlobal/.test(code));
|
||||
```
|
||||
|
||||
`oopsGlobal` should be a global variable and have a value of `5`
|
||||
`oopsGlobal` deve ser uma variável global e ter o valor de `5`
|
||||
|
||||
```js
|
||||
assert(typeof oopsGlobal != 'undefined' && oopsGlobal === 5);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 56533eb9ac21ba0edf2244c0
|
||||
title: Global vs. Local Scope in Functions
|
||||
title: Escopo Global vs Local em Funções
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c2QwKH2'
|
||||
forumTopicId: 18194
|
||||
@ -9,9 +9,9 @@ dashedName: global-vs--local-scope-in-functions
|
||||
|
||||
# --description--
|
||||
|
||||
It is possible to have both <dfn>local</dfn> and <dfn>global</dfn> variables with the same name. When you do this, the local variable takes precedence over the global variable.
|
||||
É possível ter ambas variáveis <dfn>local</dfn> e <dfn>global</dfn> com o mesmo nome. Quando você faz isso, a variável local tem precedência sobre a variável global.
|
||||
|
||||
In this example:
|
||||
Neste exemplo:
|
||||
|
||||
```js
|
||||
var someVar = "Hat";
|
||||
@ -21,27 +21,27 @@ function myFun() {
|
||||
}
|
||||
```
|
||||
|
||||
The function `myFun` will return the string `Head` because the local version of the variable is present.
|
||||
A função `myFun` retornará a string `Head` porque a versão local da variável está presente.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Add a local variable to `myOutfit` function to override the value of `outerWear` with the string `sweater`.
|
||||
Adicione uma variável local para a função `myOutfit` para sobrescrever o valor de `outerWear` com a string `sweater`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should not change the value of the global `outerWear`.
|
||||
Você não deve alterar o valor da variável global `outerWear`.
|
||||
|
||||
```js
|
||||
assert(outerWear === 'T-Shirt');
|
||||
```
|
||||
|
||||
`myOutfit` should return the string `sweater`.
|
||||
`myOutfit` deve retornar a string `sweater`.
|
||||
|
||||
```js
|
||||
assert(myOutfit() === 'sweater');
|
||||
```
|
||||
|
||||
You should not change the return statement.
|
||||
Você não deve alterar a instrução de retorno.
|
||||
|
||||
```js
|
||||
assert(/return outerWear/.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5664820f61c48e80c9fa476c
|
||||
title: Golf Code
|
||||
title: Código de Golfe
|
||||
challengeType: 1
|
||||
videoUrl: 'https://scrimba.com/c/c9ykNUR'
|
||||
forumTopicId: 18195
|
||||
@ -9,77 +9,77 @@ dashedName: golf-code
|
||||
|
||||
# --description--
|
||||
|
||||
In the game of [golf](https://en.wikipedia.org/wiki/Golf), each hole has a `par`, meaning, the average number of `strokes` a golfer is expected to make in order to sink the ball in the hole to complete the play. Depending on how far above or below `par` your `strokes` are, there is a different nickname.
|
||||
No jogo [golf](https://en.wikipedia.org/wiki/Golf), cada buraco tem um `par`, significando, o número médio de `strokes` que um golfista é esperado fazer afim de derrubar a bola no buraco para completar a jogada. Dependendo do quão distante acima ou abaixo de `par` suas `strokes` estiverem, há diferentes apelidos.
|
||||
|
||||
Your function will be passed `par` and `strokes` arguments. Return the correct string according to this table which lists the strokes in order of priority; top (highest) to bottom (lowest):
|
||||
Sua função receberá os argumentos `par` e `strokes`. Retorna a string correta de acordo com esta tabela que lista os strokes em ordem de prioridade; superior (mais alta) para o final (mais baixo):
|
||||
|
||||
<table class='table table-striped'><thead><tr><th>Strokes</th><th>Return</th></tr></thead><tbody><tr><td>1</td><td>"Hole-in-one!"</td></tr><tr><td><= par - 2</td><td>"Eagle"</td></tr><tr><td>par - 1</td><td>"Birdie"</td></tr><tr><td>par</td><td>"Par"</td></tr><tr><td>par + 1</td><td>"Bogey"</td></tr><tr><td>par + 2</td><td>"Double Bogey"</td></tr><tr><td>>= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
|
||||
<table class='table table-striped'><thead><tr><th>Strokes</th><th>Retorno</th></tr></thead><tbody><tr><td>1</td><td>"Hole-in-one!"</td></tr><tr><td><= par - 2</td><td>"Eagle"</td></tr><tr><td>par - 1</td><td>"Birdie"</td></tr><tr><td>par</td><td>"Par"</td></tr><tr><td>par + 1</td><td>"Bogey"</td></tr><tr><td>par + 2</td><td>"Double Bogey"</td></tr><tr><td>>= par + 3</td><td>"Go Home!"</td></tr></tbody></table>
|
||||
|
||||
`par` and `strokes` will always be numeric and positive. We have added an array of all the names for your convenience.
|
||||
`par` e `strokes` sempre será um número e positivo. Nós adicionamos um array com todos os nomes para sua conveniência.
|
||||
|
||||
# --hints--
|
||||
|
||||
`golfScore(4, 1)` should return the string `Hole-in-one!`
|
||||
`golfScore(4, 1)` deve retornar a string `Hole-in-one!`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(4, 2)` should return the string `Eagle`
|
||||
`golfScore(4, 2)` deve retornar a string `Eagle`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(5, 2)` should return the string `Eagle`
|
||||
`golfScore(5, 2)` deve retornar a string `Eagle`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 2) === 'Eagle');
|
||||
```
|
||||
|
||||
`golfScore(4, 3)` should return the string `Birdie`
|
||||
`golfScore(4, 3)` deve retornar a string `Birdie`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 3) === 'Birdie');
|
||||
```
|
||||
|
||||
`golfScore(4, 4)` should return the string `Par`
|
||||
`golfScore(4, 4)` deve retornar a string `Par`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 4) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(1, 1)` should return the string `Hole-in-one!`
|
||||
`golfScore(1, 1)` deve retornar a string `Hole-in-one!`
|
||||
|
||||
```js
|
||||
assert(golfScore(1, 1) === 'Hole-in-one!');
|
||||
```
|
||||
|
||||
`golfScore(5, 5)` should return the string `Par`
|
||||
`golfScore(5, 5)` deve retornar a string `Par`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 5) === 'Par');
|
||||
```
|
||||
|
||||
`golfScore(4, 5)` should return the string `Bogey`
|
||||
`golfScore(4, 5)` deve retornar a string `Bogey`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 5) === 'Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 6)` should return the string `Double Bogey`
|
||||
`golfScore(4, 6)` deve retornar a string `Double Bogey`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 6) === 'Double Bogey');
|
||||
```
|
||||
|
||||
`golfScore(4, 7)` should return the string `Go Home!`
|
||||
`golfScore(4, 7)` deve retornar a string `Go Home!`
|
||||
|
||||
```js
|
||||
assert(golfScore(4, 7) === 'Go Home!');
|
||||
```
|
||||
|
||||
`golfScore(5, 9)` should return the string `Go Home!`
|
||||
`golfScore(5, 9)` deve retornar a string `Go Home!`
|
||||
|
||||
```js
|
||||
assert(golfScore(5, 9) === 'Go Home!');
|
||||
|
@ -96,10 +96,10 @@ var contacts = [
|
||||
];
|
||||
|
||||
|
||||
function lookUpProfile(name, prop){
|
||||
// Only change code below this line
|
||||
function lookUpProfile(name, prop) {
|
||||
// Only change code below this line
|
||||
|
||||
// Only change code above this line
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
lookUpProfile("Akira", "likes");
|
||||
|
@ -90,10 +90,10 @@ testArr = [1,2,3,4,5];
|
||||
```js
|
||||
function nextInLine(arr, item) {
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
return item;
|
||||
// Only change code above this line
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
@ -128,7 +128,7 @@ function checkScope() {
|
||||
let i = 'block scope';
|
||||
console.log('Block scope i is: ', i);
|
||||
}
|
||||
|
||||
|
||||
console.log('Function scope i is: ', i);
|
||||
return i;
|
||||
}
|
||||
|
@ -52,7 +52,7 @@ assert(
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
// responseFromServer represents a response from a server
|
||||
let responseFromServer;
|
||||
|
||||
|
||||
if(responseFromServer) {
|
||||
// Change this line
|
||||
} else {
|
||||
|
@ -12,7 +12,7 @@ Promises are most useful when you have a process that takes an unknown amount of
|
||||
|
||||
```js
|
||||
myPromise.then(result => {
|
||||
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
@ -63,7 +63,7 @@ const resultIsParameter = /\.then\((function\(result\){|result|\(result\)=>)/.te
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
// responseFromServer is set to true to represent a successful response from a server
|
||||
let responseFromServer = true;
|
||||
|
||||
|
||||
if(responseFromServer) {
|
||||
resolve("We got the data");
|
||||
} else {
|
||||
@ -78,7 +78,7 @@ const makeServerRequest = new Promise((resolve, reject) => {
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
// responseFromServer is set to true to represent a successful response from a server
|
||||
let responseFromServer = true;
|
||||
|
||||
|
||||
if(responseFromServer) {
|
||||
resolve("We got the data");
|
||||
} else {
|
||||
|
@ -12,7 +12,7 @@ dashedName: handle-a-rejected-promise-with-catch
|
||||
|
||||
```js
|
||||
myPromise.catch(error => {
|
||||
|
||||
|
||||
});
|
||||
```
|
||||
|
||||
@ -63,7 +63,7 @@ const errorIsParameter = /\.catch\((function\(error\){|error|\(error\)=>)/.test(
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
// responseFromServer is set to false to represent an unsuccessful response from a server
|
||||
let responseFromServer = false;
|
||||
|
||||
|
||||
if(responseFromServer) {
|
||||
resolve("We got the data");
|
||||
} else {
|
||||
@ -82,7 +82,7 @@ makeServerRequest.then(result => {
|
||||
const makeServerRequest = new Promise((resolve, reject) => {
|
||||
// responseFromServer is set to false to represent an unsuccessful response from a server
|
||||
let responseFromServer = false;
|
||||
|
||||
|
||||
if(responseFromServer) {
|
||||
resolve("We got the data");
|
||||
} else {
|
||||
|
@ -33,7 +33,7 @@ assert(code.match(/import\s+subtract\s+from\s+('|")\.\/math_functions\.js\1/g));
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
subtract(7,4);
|
||||
|
@ -53,7 +53,7 @@ assert(
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
|
||||
|
||||
// Only change code above this line
|
||||
|
||||
uppercaseString("hello");
|
||||
|
@ -86,7 +86,7 @@ const LOCAL_FORECAST = {
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
const lowToday = LOCAL_FORECAST.today.low;
|
||||
const highToday = LOCAL_FORECAST.today.high;
|
||||
|
||||
@ -101,6 +101,6 @@ const LOCAL_FORECAST = {
|
||||
today: { low: 64, high: 77 },
|
||||
tomorrow: { low: 68, high: 80 }
|
||||
};
|
||||
|
||||
|
||||
const { today: { low: lowToday, high: highToday }} = LOCAL_FORECAST;
|
||||
```
|
||||
|
@ -77,7 +77,7 @@ const HIGH_TEMPERATURES = {
|
||||
};
|
||||
|
||||
// Only change code below this line
|
||||
|
||||
|
||||
const highToday = HIGH_TEMPERATURES.today;
|
||||
const highTomorrow = HIGH_TEMPERATURES.tomorrow;
|
||||
|
||||
|
@ -1,8 +1,7 @@
|
||||
---
|
||||
id: 587d7b8a367417b2b2512b4c
|
||||
title: >-
|
||||
Use Destructuring Assignment with the Rest Parameter to Reassign Array
|
||||
Elements
|
||||
Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements
|
||||
challengeType: 1
|
||||
forumTopicId: 301218
|
||||
dashedName: >-
|
||||
|
@ -14,7 +14,7 @@ These are classically called <dfn>getters</dfn> and <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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
```js
|
||||
class Book {
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user