chore(i18n): download curriculum manually (#42835)

This commit is contained in:
Mrugesh Mohapatra
2021-07-14 21:02:51 +05:30
committed by GitHub
parent 2f8c5619ff
commit fc0511bd91
126 changed files with 1128 additions and 1124 deletions

View File

@ -11,7 +11,7 @@ dashedName: create-decimal-numbers-with-javascript
También podemos almacenar números decimales en variables. Los números decimales a veces se denominan números de <dfn>coma flotante</dfn> o <dfn>flotantes</dfn>.
**Nota:** No todos los números reales pueden representarse con precisión en <dfn>coma flotante</dfn>. Esto puede llevar a errores de redondeo. [Detalles aquí](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
**Nota:** No todos los números reales pueden representarse con precisión en <dfn>coma flotante</dfn>. Esto puede llevar a errores de redondeo. [Detalles aquí](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems).
# --instructions--

View File

@ -8,21 +8,21 @@ dashedName: use--for-a-more-concise-conditional
# --description--
The `if/else` statements worked in the last challenge, but there's a more concise way to achieve the same result. Imagine that you are tracking several conditions in a component and you want different elements to render depending on each of these conditions. If you write a lot of `else if` statements to return slightly different UIs, you may repeat code which leaves room for error. Instead, you can use the `&&` logical operator to perform conditional logic in a more concise way. This is possible because you want to check if a condition is `true`, and if it is, return some markup. Here's an example:
Las sentencias `if/else` funcionaron en el último desafío, pero hay una manera más concisa de lograr el mismo resultado. Imagina que estás rastreando varias condiciones en un componente y deseas que diferentes elementos se rendericen dependiendo de cada una de estas condiciones. Si escribes un montón de sentencias `else if` para devolver UIs ligeramente diferentes, puedes repetir código que deja espacio para el error. En su lugar, puedes usar el operador lógico `&&` para realizar lógica condicional de una manera más concisa. Esto es posible porque quieres comprobar si una condición es `true`, y si es así, devuelve algún código. Aquí hay un ejemplo:
```jsx
{condition && <p>markup</p>}
```
If the `condition` is `true`, the markup will be returned. If the condition is `false`, the operation will immediately return `false` after evaluating the `condition` and return nothing. You can include these statements directly in your JSX and string multiple conditions together by writing `&&` after each one. This allows you to handle more complex conditional logic in your `render()` method without repeating a lot of code.
Si la `condition` es `true`, el código será devuelto. Si la condición es `false`, la operación devolverá inmediatamente `false` después de evaluar la `condition` y no devolverá nada. Puedes incluir estas sentencias directamente en tu JSX y encadenar varias condiciones juntas escribiendo `&&` después de cada uno. Esto te permite manejar una lógica condicional más compleja en tu método `render()` sin repetir un montón de código.
# --instructions--
Solve the previous example again, so the `h1` only renders if `display` is `true`, but use the `&&` logical operator instead of an `if/else` statement.
Resuelve el ejemplo anterior de nuevo, de este modo el `h1` solo renderiza si `display` es `true`, pero usa el operador lógico `&&` en lugar de una sentencia `if/else`.
# --hints--
`MyComponent` should exist and render.
`MyComponent` debe existir y renderizar.
```js
assert(
@ -33,7 +33,7 @@ assert(
);
```
When `display` is set to `true`, a `div`, `button`, and `h1` should render.
Cuando `display` se establece en `true`, un `div`, `button`, y `h1` debe renderizarse.
```js
async () => {
@ -54,7 +54,7 @@ async () => {
};
```
When `display` is set to `false`, only a `div` and `button` should render.
Cuando `display` se establece en `false`, solo un `div` y un `button` debe renderizarse.
```js
async () => {
@ -75,7 +75,7 @@ async () => {
};
```
The render method should use the `&&` logical operator to check the condition of `this.state.display`.
El método renderizador debe usar el operador lógico `&&` para comprobar la condición de `this.state.display`.
```js
(getUserInput) => assert(getUserInput('index').includes('&&'));

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036187
title: Use a Ternary Expression for Conditional Rendering
title: Utiliza una expresión ternaria para el renderizado condicional
challengeType: 6
forumTopicId: 301414
dashedName: use-a-ternary-expression-for-conditional-rendering
@ -8,7 +8,7 @@ dashedName: use-a-ternary-expression-for-conditional-rendering
# --description--
Before moving on to dynamic rendering techniques, there's one last way to use built-in JavaScript conditionals to render what you want: the <dfn>ternary operator</dfn>. The ternary operator is often utilized as a shortcut for `if/else` statements in JavaScript. They're not quite as robust as traditional `if/else` statements, but they are very popular among React developers. One reason for this is because of how JSX is compiled, `if/else` statements can't be inserted directly into JSX code. You might have noticed this a couple challenges ago — when an `if/else` statement was required, it was always *outside* the `return` statement. Ternary expressions can be an excellent alternative if you want to implement conditional logic within your JSX. Recall that a ternary operator has three parts, but you can combine several ternary expressions together. Here's the basic syntax:
Antes de pasar a técnicas de renderizado dinámico, hay una última forma de usar condicionales de JavaScript incorporados para representar lo que quieres: el <dfn>operador ternario</dfn>. El operador ternario a menudo es utilizado como un acceso directo para las sentencias `if/else` en JavaScript. No son tan robustas como las sentencias tradicionales `if/else`, pero son muy populares entre los desarrolladores de React. Una de las razones de esto es debido a cómo se compila JSX, las sentencias `if/else` no se pueden insertar directamente en el código JSX. Puede que hayas notado esto hace un par de desafíos, cuando se requirió una sentencia `if/else`, siempre estaba *fuera* de la sentencia `return`. Las expresiones ternarias pueden ser una excelente alternativa si deseas implementar lógica condicional dentro de tu JSX. Recuerda que un operador ternario tiene tres partes, pero puedes combinar varias expresiones ternarias juntas. Aquí está la sintaxis básica:
```jsx
condition ? expressionIfTrue : expressionIfFalse;
@ -16,13 +16,13 @@ condition ? expressionIfTrue : expressionIfFalse;
# --instructions--
The code editor has three constants defined within the `CheckUserAge` component's `render()` method. They are called `buttonOne`, `buttonTwo`, and `buttonThree`. Each of these is assigned a simple JSX expression representing a button element. First, initialize the state of `CheckUserAge` with `input` and `userAge` both set to values of an empty string.
El editor de código tiene tres constantes definidas dentro del método `render()` del componente `CheckUserAge`. Estas se llaman `buttonOne`, `buttonTwo` y `buttonThree`. A cada una de estas se le asigna una expresión JSX simple que representa un elemento de botón. Primero, inicializa el estado de `CheckUserAge` con `input` y `userAge` ambos configurados a valores de una cadena vacía.
Once the component is rendering information to the page, users should have a way to interact with it. Within the component's `return` statement, set up a ternary expression that implements the following logic: when the page first loads, render the submit button, `buttonOne`, to the page. Then, when a user enters their age and clicks the button, render a different button based on the age. If a user enters a number less than `18`, render `buttonThree`. If a user enters a number greater than or equal to `18`, render `buttonTwo`.
Una vez que el componente está renderizando información a la página, los usuarios deberían tener una forma de interactuar con ella. Dentro de la declaración `return` del componente, configura una expresión ternaria que implementa la siguiente lógica: cuando la página carga por primera vez, renderiza el botón de envío, `buttonOne`, a la página. Luego, cuando un usuario ingrese su edad y haga clic en el botón, renderiza un botón diferente basado en la edad. Si un usuario introduce un número menor que `18`, renderiza `buttonThree`. Si un usuario introduce un número mayor o igual a `18`, renderiza `buttonTwo`.
# --hints--
The `CheckUserAge` component should render with a single `input` element and a single `button` element.
El componente `CheckUserAge` debe renderizarse con un solo elemento `input` y un solo elemento `button`.
```js
assert(
@ -33,7 +33,7 @@ assert(
);
```
The `CheckUserAge` component's state should be initialized with a property of `userAge` and a property of `input`, both set to a value of an empty string.
El estado del componente `CheckUserAge` debe inicializarse con una propiedad de `userAge` y una propiedad de `input`, ambos establecidos a un valor de una cadena vacía.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
When the `CheckUserAge` component is first rendered to the DOM, the `button`'s inner text should be Submit.
Cuando el componente `CheckUserAge` es renderizado por primera vez en el DOM, el texto interno del `button` debe decir "Submit".
```js
assert(
@ -51,7 +51,7 @@ assert(
);
```
When a number of less than 18 is entered into the `input` element and the `button` is clicked, the `button`'s inner text should read `You Shall Not Pass`.
Cuando se introduce un número menor de 18 en el elemento `input` y se hace clic en el `button`, el texto interno del `button` debe decir `You Shall Not Pass`.
```js
(() => {
@ -83,7 +83,7 @@ When a number of less than 18 is entered into the `input` element and the `butto
})();
```
When a number greater than or equal to 18 is entered into the `input` element and the `button` is clicked, the `button`'s inner text should read `You May Enter`.
Cuando se introduce un número mayor o igual a 18 en el elemento `input` y se hace clic en el `button` el texto interno del `button` debe decir `You May Enter`.
```js
(() => {
@ -115,7 +115,7 @@ When a number greater than or equal to 18 is entered into the `input` element an
})();
```
Once a number has been submitted, and the value of the `input` is once again changed, the `button` should return to reading `Submit`.
Una vez que un número ha sido enviado, y el valor del `input` se cambia una vez más, el `button` debe decir `Submit`.
```js
(() => {
@ -156,7 +156,7 @@ Once a number has been submitted, and the value of the `input` is once again cha
})();
```
Your code should not contain any `if/else` statements.
Tu código no debe contener ninguna sentencia `if/else`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036183
title: Use Advanced JavaScript in React Render Method
title: Usa JavaScript avanzado en el método render de React
challengeType: 6
forumTopicId: 301415
dashedName: use-advanced-javascript-in-react-render-method
@ -8,17 +8,17 @@ dashedName: use-advanced-javascript-in-react-render-method
# --description--
In previous challenges, you learned how to inject JavaScript code into JSX code using curly braces, `{ }`, for tasks like accessing props, passing props, accessing state, inserting comments into your code, and most recently, styling your components. These are all common use cases to put JavaScript in JSX, but they aren't the only way that you can utilize JavaScript code in your React components.
En desafíos anteriores, aprendiste cómo inyectar código JavaScript en código JSX usando llaves, `{ }`, para tareas como acceder a props, pasar props, acceder al state, insertar comentarios en tu código y, más recientemente, diseñar tus componentes. Todos estos son casos de uso común para poner JavaScript en JSX, pero no son la única manera de utilizar código JavaScript en tus componentes React.
You can also write JavaScript directly in your `render` methods, before the `return` statement, ***without*** inserting it inside of curly braces. This is because it is not yet within the JSX code. When you want to use a variable later in the JSX code *inside* the `return` statement, you place the variable name inside curly braces.
También puedes escribir JavaScript directamente en los métodos `render`, antes de la sentencia `return`, ***sin*** insertarlo dentro de llaves. Esto es porque aún no está dentro del código JSX. Cuando quieras utilizar una variable en el código JSX *dentro* de la sentencia `return`, colocas el nombre de la variable dentro de llaves.
# --instructions--
In the code provided, the `render` method has an array that contains 20 phrases to represent the answers found in the classic 1980's Magic Eight Ball toy. The button click event is bound to the `ask` method, so each time the button is clicked a random number will be generated and stored as the `randomIndex` in state. On line 52, delete the string `change me!` and reassign the `answer` const so your code randomly accesses a different index of the `possibleAnswers` array each time the component updates. Finally, insert the `answer` const inside the `p` tags.
En el código proporcionado, el método `render` tiene un arreglo que contiene 20 frases para representar las respuestas encontradas en el clásico juego "Magic Eight Ball" de los años ochenta. El evento clic del botón está vinculado al método `ask`, por lo que cada vez que se haga clic en el botón se generará un número aleatorio y se almacenará como el `randomIndex` en el state. En la línea 52, elimina la cadena `change me!` y reasigna la constante `answer` para que tu código acceda aleatoriamente a un índice diferente del arreglo `possibleAnswers` cada vez que se actualiza el componente. Finalmente, inserta la constante `answer` dentro de las etiquetas `p`.
# --hints--
The `MagicEightBall` component should exist and should render to the page.
El componente `MagicEightBall` debe existir y renderizarse en la página.
```js
assert.strictEqual(
@ -28,7 +28,7 @@ assert.strictEqual(
);
```
`MagicEightBall`'s first child should be an `input` element.
El primer elemento hijo de `MagicEightBall` debe ser un elemento `input`.
```js
assert.strictEqual(
@ -40,7 +40,7 @@ assert.strictEqual(
);
```
`MagicEightBall`'s third child should be a `button` element.
El tercer elemento hijo de `MagicEightBall` debe ser un elemento `button`.
```js
assert.strictEqual(
@ -52,7 +52,7 @@ assert.strictEqual(
);
```
`MagicEightBall`'s state should be initialized with a property of `userInput` and a property of `randomIndex` both set to a value of an empty string.
El estado de `MagicEightBall` debe inicializarse con una propiedad de `userInput` y una propiedad de `randomIndex` juntas establecidas como cadenas de texto vacías.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
When `MagicEightBall` is first mounted to the DOM, it should return an empty `p` element.
Cuando `MagicEightBall` se monte por primera vez en el DOM, debe devolver un elemento `p` vacío.
```js
assert(
@ -71,7 +71,7 @@ assert(
);
```
When text is entered into the `input` element and the button is clicked, the `MagicEightBall` component should return a `p` element that contains a random element from the `possibleAnswers` array.
Cuando se introduce texto en el elemento `input` y se hace clic en el botón, el componente `MagicEightBall` debe devolver un elemento `p` que contiene un elemento aleatorio del arreglo `possibleAnswers`.
```js
(() => {

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403618c
title: Use Array.filter() to Dynamically Filter an Array
title: Usa Array.filter() para filtrar dinámicamente un arreglo
challengeType: 6
forumTopicId: 301416
dashedName: use-array-filter-to-dynamically-filter-an-array
@ -8,7 +8,7 @@ dashedName: use-array-filter-to-dynamically-filter-an-array
# --description--
The `map` array method is a powerful tool that you will use often when working with React. Another method related to `map` is `filter`, which filters the contents of an array based on a condition, then returns a new array. For example, if you have an array of users that all have a property `online` which can be set to `true` or `false`, you can filter only those users that are online by writing:
El método de arreglo `map` es una potente herramienta que puedes usar a menudo al trabajar con React. Otro método relacionado con `map` es `filter`, que filtra el contenido de un arreglo basado en una condición, luego devuelve un nuevo arreglo. Por ejemplo, si tienes un arreglo de usuarios que todos tienen una propiedad `online` que puede establecerse en `true` o `false`, puedes filtrar sólo aquellos usuarios que estén en línea escribiendo:
```js
let onlineUsers = users.filter(user => user.online);
@ -16,11 +16,11 @@ let onlineUsers = users.filter(user => user.online);
# --instructions--
In the code editor, `MyComponent`'s `state` is initialized with an array of users. Some users are online and some aren't. Filter the array so you see only the users who are online. To do this, first use `filter` to return a new array containing only the users whose `online` property is `true`. Then, in the `renderOnline` variable, map over the filtered array, and return a `li` element for each user that contains the text of their `username`. Be sure to include a unique `key` as well, like in the last challenges.
En el editor de código, el `state` de `MyComponent` es inicializado con un arreglo de usuarios. Algunos usuarios están conectados y otros no. Filtra el arreglo para que sólo veas a los usuarios que están en línea. Para hacer esto, primero usa `filter` para devolver un nuevo arreglo que contiene solo a los usuarios cuya propiedad `online` es `true`. Luego, en la variable `renderOnline`, asigna sobre el arreglo filtrado, y devuelve un elemento `li` para cada usuario que contiene el texto de su `username`. Asegúrate de incluir también una única `key`, como en los últimos desafíos.
# --hints--
`MyComponent` should exist and render to the page.
`MyComponent` debe existir y renderizarse en la página.
```js
assert.strictEqual(
@ -29,7 +29,7 @@ assert.strictEqual(
);
```
`MyComponent`'s state should be initialized to an array of six users.
El estado de `MyComponent` debe inicializarse a un arreglo de seis usuarios.
```js
assert(
@ -40,7 +40,7 @@ assert(
);
```
`MyComponent` should return a `div`, an `h1`, and then an unordered list containing `li` elements for every user whose online status is set to `true`.
`MyComponent` debe devolver un `div`, un `h1`, y luego una lista desordenada que contiene elementos `li` para cada usuario cuyo estado de conexión se establece en `true`.
```js
(() => {
@ -83,7 +83,7 @@ assert(
})();
```
`MyComponent` should render `li` elements that contain the `username` of each online user.
`MyComponent` debe renderizar elementos `li` que contienen el `username` de cada usuario en línea.
```js
(() => {
@ -109,7 +109,7 @@ assert(
})();
```
Each list item element should have a unique `key` attribute.
Cada elemento de la lista debe tener un atributo `key` único.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403618a
title: Use Array.map() to Dynamically Render Elements
title: Utiliza Array.map() para renderizar dinámicamente los elementos
challengeType: 6
forumTopicId: 301417
dashedName: use-array-map-to-dynamically-render-elements
@ -8,21 +8,21 @@ dashedName: use-array-map-to-dynamically-render-elements
# --description--
Conditional rendering is useful, but you may need your components to render an unknown number of elements. Often in reactive programming, a programmer has no way to know what the state of an application is until runtime, because so much depends on a user's interaction with that program. Programmers need to write their code to correctly handle that unknown state ahead of time. Using `Array.map()` in React illustrates this concept.
El renderizado condicional es útil, pero es posible que necesites tus componentes para renderizar un número desconocido de elementos. A menudo en la programación reactiva, un programador no tiene forma de saber cuál es el estado de una aplicación hasta el tiempo de ejecución, porque mucho depende de la interacción de un usuario con ese programa. Los programadores necesitan escribir su código para manejar correctamente ese estado desconocido antes de tiempo. Usar `Array.map()` en React ilustra este concepto.
For example, you create a simple "To Do List" app. As the programmer, you have no way of knowing how many items a user might have on their list. You need to set up your component to dynamically render the correct number of list elements long before someone using the program decides that today is laundry day.
Por ejemplo, crea una aplicación simple "To Do List". Como programador, no tienes forma de saber cuántos elementos puede tener un usuario en su lista. Necesitas configurar tu componente para renderizar dinámicamente el número correcto de elementos de la lista mucho antes de que alguien que use el programa decida que hoy es día de lavandería.
# --instructions--
The code editor has most of the `MyToDoList` component set up. Some of this code should look familiar if you completed the controlled form challenge. You'll notice a `textarea` and a `button`, along with a couple of methods that track their states, but nothing is rendered to the page yet.
El editor de código tiene la mayoría del componente `MyToDoList` configurado. Parte de este código debería parecer familiar si completaste el desafío de formulario controlado. Vas a notar un `textarea` y un `button`, junto con un par de métodos que rastrean sus estados, pero aún no se muestra nada a la página.
Inside the `constructor`, create a `this.state` object and define two states: `userInput` should be initialized as an empty string, and `toDoList` should be initialized as an empty array. Next, delete the comment in the `render()` method next to the `items` variable. In its place, map over the `toDoList` array stored in the component's internal state and dynamically render a `li` for each item. Try entering the string `eat, code, sleep, repeat` into the `textarea`, then click the button and see what happens.
Dentro del `constructor`, crea un objeto `this.state` y define dos estados: `userInput` que debe inicializarse como una cadena vacía, y `toDoList` que debe inicializarse como un arreglo vacío. Luego, elimina el comentario junto a la variable `items` del método `render()`. En su lugar, utiliza la función map() para recorrer el arreglo `toDoList` almacenado en el internal state del componente y renderizar un `li` por cada item. Intenta introducir la cadena `eat, code, sleep, repeat` dentro del `textarea`, haz clic en el botón y ve qué sucede.
**Note:** You may know that all sibling child elements created by a mapping operation like this do need to be supplied with a unique `key` attribute. Don't worry, this is the topic of the next challenge.
**Nota:** Puede que sepas que todos los elementos hijos hermanos creados por una operación map como ésta necesitan poseer un atributo `key` único. No te preocupes, este es el tema de nuestro próximo desafío.
# --hints--
The MyToDoList component should exist and render to the page.
El componente MyToDoList debe existir y mostrarse en la página.
```js
assert(
@ -33,7 +33,7 @@ assert(
);
```
The first child of `MyToDoList` should be a `textarea` element.
El primer hijo de `MyToDoList` debe ser un elemento `textarea`.
```js
assert(
@ -47,7 +47,7 @@ assert(
);
```
The second child of `MyToDoList` should be a `br` element.
El segundo hijo de `MyToDoList` debe ser un elemento `br`.
```js
assert(
@ -60,7 +60,7 @@ assert(
);
```
The third child of `MyToDoList` should be a `button` element.
El tercer hijo de `MyToDoList` debe ser un elemento `button`.
```js
assert(
@ -74,7 +74,7 @@ assert(
);
```
The state of `MyToDoList` should be initialized with `toDoList` as an empty array.
El estado de `MyToDoList` debe inicializarse con un arreglo vacío `toDoList`.
```js
assert(
@ -89,7 +89,7 @@ assert(
);
```
The state of `MyToDoList` should be initialized with `userInput` as an empty string.
El estado de `MyToDoList` debe ser inicializado con una cadena vacía `userInput`.
```js
assert(
@ -104,7 +104,7 @@ assert(
);
```
When the `Create List` button is clicked, the `MyToDoList` component should dynamically return an unordered list that contains a list item element for every item of a comma-separated list entered into the `textarea` element.
Cuando el botón `Create List` es presionado, el componente `MyToDoList` debe devolver dinámicamente una lista desordenada que contenga un artículo por cada elemento de una lista separada por coma dentro del elemento `textarea`.
```js
(() => {

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403616b
title: Use Default Props
title: Usa props predeterminadas
challengeType: 6
forumTopicId: 301418
dashedName: use-default-props
@ -8,15 +8,15 @@ dashedName: use-default-props
# --description--
React also has an option to set default props. You can assign default props to a component as a property on the component itself and React assigns the default prop if necessary. This allows you to specify what a prop value should be if no value is explicitly provided. For example, if you declare `MyComponent.defaultProps = { location: 'San Francisco' }`, you have defined a location prop that's set to the string `San Francisco`, unless you specify otherwise. React assigns default props if props are undefined, but if you pass `null` as the value for a prop, it will remain `null`.
React también tiene una opción para establecer props predeterminadas. Puedes asignar props predeterminadas a un componente como si fueran una propiedad dentro del propio componente y React asigna la prop predeterminada si es necesario. Esto te permite especificar cuál debe ser el valor de una prop si no se provee un valor específico. Por ejemplo, si declaras `MyComponent.defaultProps = { location: 'San Francisco' }`, has definido una prop de localización que se establece en la cadena `San Francisco`, a menos que especifiques lo contrario. React asigna props predeterminadas si estas no están definidas, pero si pasas el valor `null` como valor para una prop, este permanecerá `null`.
# --instructions--
The code editor shows a `ShoppingCart` component. Define default props on this component which specify a prop `items` with a value of `0`.
El editor de código muestra un componente `ShoppingCart`. Define props predeterminadas en este componente que especifican una prop `items` con un valor de `0`.
# --hints--
The `ShoppingCart` component should render.
El componente `ShoppingCart` debe renderizarse.
```js
assert(
@ -27,7 +27,7 @@ assert(
);
```
The `ShoppingCart` component should have a default prop of `{ items: 0 }`.
El componente `ShoppingCart` debe tener una prop predeterminada de `{ items: 0 }`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d403616d
title: Use PropTypes to Define the Props You Expect
title: Usa PropTypes para definir las props que esperas
challengeType: 6
forumTopicId: 301419
dashedName: use-proptypes-to-define-the-props-you-expect
@ -8,25 +8,25 @@ dashedName: use-proptypes-to-define-the-props-you-expect
# --description--
React provides useful type-checking features to verify that components receive props of the correct type. For example, your application makes an API call to retrieve data that you expect to be in an array, which is then passed to a component as a prop. You can set `propTypes` on your component to require the data to be of type `array`. This will throw a useful warning when the data is of any other type.
React proporciona características útiles de validación de tipos para verificar que los componentes reciban las props del tipo correcto. Por ejemplo, tu aplicación hace una llamada a un API para obtener datos que se esperan que sea un arreglo, el cual es pasado al componente como una prop. Puedes establecer `propTypes` en tu componente para que los datos sean de tipo `array`. Esto arrojará una advertencia útil cuando los datos sean de otro tipo.
It's considered a best practice to set `propTypes` when you know the type of a prop ahead of time. You can define a `propTypes` property for a component in the same way you defined `defaultProps`. Doing this will check that props of a given key are present with a given type. Here's an example to require the type `function` for a prop called `handleClick`:
Se considera una muy buena práctica definir los `propTypes` cuando conoces el tipo de una propiedad con antelación. Puedes definir una propiedad `propTypes` para un componente de la misma manera que defines `defaultProps`. Al hacer esto, se validará que las props de una clave determinada están presentes con un tipo específico. Aquí hay un ejemplo para validar el tipo `function` para una prop llamada `handleClick`:
```js
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
```
In the example above, the `PropTypes.func` part checks that `handleClick` is a function. Adding `isRequired` tells React that `handleClick` is a required property for that component. You will see a warning if that prop isn't provided. Also notice that `func` represents `function`. Among the seven JavaScript primitive types, `function` and `boolean` (written as `bool`) are the only two that use unusual spelling. In addition to the primitive types, there are other types available. For example, you can check that a prop is a React element. Please refer to the [documentation](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type) for all of the options.
En el ejemplo anterior, la parte de `PropTypes.func` verifica que `handleClick` es una funcn. Añadir `isRequired` le dice a React que `handleClick` es una propiedad obligatoria para ese componente. Verás una advertencia si no se proporciona esa propiedad. También ten en cuenta que `func` representa `function`. Entre los siete tipos primitivos de JavaScript, `function` y `boolean` (escrito como `bool`) son los únicos dos que utilizan ortografía diferente. Además de los tipos primitivos, hay otros tipos disponibles. Por ejemplo, puedes validar si una prop es un elemento React. Por favor, consulta la [documentación](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type) para todas las opciones.
**Note:** As of React v15.5.0, `PropTypes` is imported independently from React, like this: `import PropTypes from 'prop-types';`
**Nota:** A partir de React v15.5.0, `PropTypes` se importa de manera independiente de React, así: `import PropTypes from 'prop-types';`
# --instructions--
Define `propTypes` for the `Items` component to require `quantity` as a prop and verify that it is of type `number`.
Define `propTypes` para el componente `Items` de tal manera que `quantity` sea una prop obligatoria y verificar que sea de tipo `number`.
# --hints--
The `ShoppingCart` component should render.
El componente `ShoppingCart` debe renderizarse.
```js
assert(
@ -37,7 +37,7 @@ assert(
);
```
The `Items` component should render.
El componente `Items` debe renderizarse.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
The `Items` component should include a `propTypes` check to require a value for `quantity` and ensure that its value is a number.
El componente `Items` debe incluir una comprobación `propTypes` para requerir un valor para `quantity` y asegurar que su valor es un número.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 5a24c314108439a4d4036165
title: Use React to Render Nested Components
title: Utiliza React para procesar componentes anidados
challengeType: 6
forumTopicId: 301420
dashedName: use-react-to-render-nested-components
@ -8,23 +8,23 @@ dashedName: use-react-to-render-nested-components
# --description--
The last challenge showed a simple way to compose two components, but there are many different ways you can compose components with React.
El último desafío mostró una manera simple de organizar dos componentes, pero hay muchas maneras diferentes de organizar componentes con React.
Component composition is one of React's powerful features. When you work with React, it is important to start thinking about your user interface in terms of components like the App example in the last challenge. You break down your UI into its basic building blocks, and those pieces become the components. This helps to separate the code responsible for the UI from the code responsible for handling your application logic. It can greatly simplify the development and maintenance of complex projects.
La composición de componentes es una de las características más poderosas de React. Cuando trabajas con React, es importante comenzar a pensar en tu interfaz de usuario en términos de componentes, como el ejemplo App del último desafío. Debes dividir tu UI en sus bloques básicos de construcción, y esas piezas se convierten en los componentes. Esto ayuda a separar el código responsable de la interfaz de usuario del código responsable de manejar la lógica de tu aplicación. Esto puede simplificar enormemente el desarrollo y el mantenimiento de proyectos complejos.
# --instructions--
There are two functional components defined in the code editor, called `TypesOfFruit` and `Fruits`. Take the `TypesOfFruit` component and compose it, or *nest* it, within the `Fruits` component. Then take the `Fruits` component and nest it within the `TypesOfFood` component. The result should be a child component, nested within a parent component, which is nested within a parent component of its own!
Hay dos componentes funcionales definidos en el editor de código, llamados `TypesOfFruit` y `Fruits`. Toma el componente `TypesOfFruit` y organízalo, o *anídalo*, dentro del componente `Fruits`. Luego toma el componente `Fruits` y anídalo dentro del componente `TypesOfFood`. El resultado debe ser un componente hijo, anidado dentro de un componente padre, ¡que a su vez está anidado dentro de un componente padre!
# --hints--
The `TypesOfFood` component should return a single `div` element.
El componente `TypesOfFood` debe devolver un solo elemento `div`.
```js
assert(Enzyme.shallow(React.createElement(TypesOfFood)).type() === 'div');
```
The `TypesOfFood` component should return the `Fruits` component.
El componente `TypesOfFood` debe devolver el componente `Fruits`.
```js
assert(
@ -33,7 +33,7 @@ assert(
);
```
The `Fruits` component should return the `TypesOfFruit` component.
El componente `Fruits` debe devolver el componente `TypesOfFruit`.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The `TypesOfFruit` component should return the `h2` and `ul` elements.
El componente `TypesOfFruit` debe devolver los elementos `h2` y `ul`.
```js
assert(

View File

@ -26,9 +26,11 @@ As you can see, the body is encoded like the query string. This is the default f
# --instructions--
Install the `body-parser` module in your `package.json`. Then, `require` it at the top of the file. Store it in a variable named `bodyParser`. The middleware to handle urlencoded data is returned by `bodyParser.urlencoded({extended: false})`. Pass to `app.use()` the function returned by the previous method call. As usual, the middleware must be mounted before all the routes which need it.
Install the `body-parser` module in your `package.json`. Then, `require` it at the top of the file. Store it in a variable named `bodyParser`. The middleware to handle urlencoded data is returned by `bodyParser.urlencoded({extended: false})`. Pass the function returned by the previous method call to `app.use()`. As usual, the middleware must be mounted before all the routes that depend on it.
**Note:** `extended=false` is a configuration option that tells the parser to use the classic encoding. When using it, values can be only strings or arrays. The extended version allows more data flexibility, but it is outmatched by JSON.
**Note:** `extended` is a configuration option that tells `body-parser` which parsing needs to be used. When `extended=false` it uses the classic encoding `querystring` library. When `extended=true` it uses `qs` library for parsing.
When using `extended=false`, values can be only strings or arrays. The object returned when using `querystring` does not prototypically inherit from the default JavaScript `Object`, which means functions like `hasOwnProperty`, `toString` will not be available. The extended version allows more data flexibility, but it is outmatched by JSON.
# --hints--

View File

@ -11,7 +11,7 @@ dashedName: create-decimal-numbers-with-javascript
Possiamo memorizzare nelle variabili anche i numeri decimali. I numeri decimali a volte sono indicati come numeri <dfn>in virgola mobile (floating point)</dfn> o <dfn>floats</dfn>.
**Nota:** Non tutti i numeri reali possono essere accuratamente rappresentati in <dfn>floating point</dfn>. Ciò può portare a errori di arrotondamento. [Dettagli qui](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
**Nota:** Non tutti i numeri reali possono essere accuratamente rappresentati in <dfn>floating point</dfn>. Ciò può portare a errori di arrotondamento. [Dettagli qui](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems).
# --instructions--

View File

@ -10,11 +10,11 @@ dashedName: access-props-using-this-props
Le ultime sfide hanno mostrato i modi fondamentali per passare le proprietà ai componenti figli. Ma cosa succede se il componente figlio a cui stai passando una prop è un componente di classe ES6, piuttosto che un componente funzionale senza stato? Il componente di classe ES6 utilizza una convenzione leggermente diversa per accedere alle proprietà.
Ogni volta che fai riferimento a un componente di classe all'interno di sé stesso, usi la parola chiave `this`. Per accedere alle proprietà all'interno di un componente di classe, premetti `this` al codice che usi per accedervi. Ad esempio, se un componente di classe ES6 ha una prop chiamata `data`, scriverai `{this.props.data}` in JSX.
Ogni volta che fai riferimento a un componente di classe all'interno di sé stesso, usa la parola chiave `this`. Per accedere alle proprietà all'interno di un componente di classe, premetti `this` al codice che usi per accedervi. Ad esempio, se un componente di classe ES6 ha una prop chiamata `data`, scriverai `{this.props.data}` in JSX.
# --instructions--
Mostra un'istanza del componente `ReturnTempPassword` nel componente padre `ResetPassword`. Qui, dai a `ReturnTempPassword` una prop di `tempPassword` e assegnale un valore stringa di almeno 8 caratteri. All'interno del figlio, `ReturnTempPassword`, accedi alla prop `tempPassword` all'interno dei tag `strong` per assicurarti che l'utente veda la password temporanea.
Mostra un'istanza del componente `ReturnTempPassword` nel componente genitore `ResetPassword`. Qui, dai a `ReturnTempPassword` una prop di `tempPassword` e assegnale un valore stringa di almeno 8 caratteri. All'interno del figlio, `ReturnTempPassword`, accedi alla prop `tempPassword` all'interno dei tag `strong` per assicurarti che l'utente veda la password temporanea.
# --hints--

View File

@ -24,7 +24,7 @@ class Kitten extends React.Component {
}
```
Questo crea una classe ES6 `Kitten` che estende la classe `React.Component`. Così la classe `Kitten` ora ha accesso a molte funzionalità React utili, come lo stato locale e gli agganci del ciclo di vita. Non preoccuparti se non hai ancora familiarità con questi termini, saranno coperti in maggior dettaglio nelle sfide successive. Nota anche che la classe `Kitten` ha un `constructor` definito al suo interno che chiama `super()`. Esso usa `super()` per chiamare il costruttore della classe padre, in questo caso `React.Component`. Il costruttore è un metodo speciale usato durante l'inizializzazione degli oggetti creati con la parola chiave `class`. È buona pratica chiamare il `constructor` di un componente con `super` e passare le `props` ad entrambi. Questo assicura che il componente sia inizializzato correttamente. Per adesso, sappi che è uno standard includere questo codice. Presto vedrai altri usi per il costruttore e le `props`.
Questo crea una classe ES6 `Kitten` che estende la classe `React.Component`. Così la classe `Kitten` ora ha accesso a molte funzionalità React utili, come lo stato locale (local state) e gli agganci del ciclo di vita (lifecycle hook). Non preoccuparti se non hai ancora familiarità con questi termini, saranno coperti in maggior dettaglio nelle sfide successive. Nota anche che la classe `Kitten` ha un `constructor` definito al suo interno che chiama `super()`. Esso usa `super()` per chiamare il costruttore della classe genitore, in questo caso `React.Component`. Il costruttore è un metodo speciale usato durante l'inizializzazione degli oggetti creati con la parola chiave `class`. È buona pratica chiamare il `constructor` di un componente con `super` e passare le `props` ad entrambi. Questo assicura che il componente sia inizializzato correttamente. Per adesso, sappi che è uno standard includere questo codice. Presto vedrai altri usi per il costruttore e le `props`.
# --instructions--

View File

@ -8,9 +8,9 @@ dashedName: use-proptypes-to-define-the-props-you-expect
# --description--
React fornisce utili funzioni di verifica del tipo per verificare che i componenti ricevano proprietà del tipo corretto. Ad esempio, la tua applicazione effettua una chiamata API per recuperare dei dati che ti aspetti essere in un array, che viene poi passato a un componente come proprietà. Puoi impostare `propTypes` sul tuo componente per richiedere che i dati siano di tipo `array`. Questo generà un avviso utile quando i dati saranno di qualsiasi altro tipo.
React fornisce utili funzioni di verifica del tipo per verificare che i componenti ricevano proprietà del tipo corretto. Ad esempio, la tua applicazione effettua una chiamata API per recuperare dei dati che ti aspetti essere in un array, che viene poi passato a un componente come proprietà. Puoi impostare `propTypes` sul tuo componente per richiedere che i dati siano di tipo `array`. Questo genera un avviso utile quando i dati saranno di qualsiasi altro tipo.
È considerata una buona pratica impostare `propTypes` quando si conosce il tipo di una prop in anticipo. Puoi definire una proprietà `propTypes` per un componente nello stesso modo in cui hai definito `defaultProps`. In questo modo si verificherà che la prop con una data chiave sia presenti con un dato tipo. Ecco un esempio per richiedere il tipo `function` per una prop chiamata `handleClick`:
È considerata una buona pratica impostare `propTypes` quando si conosce il tipo di una prop in anticipo. Puoi definire una proprietà `propTypes` per un componente nello stesso modo in cui hai definito `defaultProps`. In questo modo verrà verificato che la prop con una data chiave sia presente con un dato tipo. Ecco un esempio per richiedere il tipo `function` per una prop chiamata `handleClick`:
```js
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }

View File

@ -26,13 +26,15 @@ Come puoi vedere, il corpo è codificato come la query string. Questo è il form
# --instructions--
Installa il modulo `body-parser` nel tuo `package.json`. Poi, richiedilo con `require` all'inizio del file. Memorizzalo in una variabile chiamata `bodyParser`. Il middleware per gestire i dati urlencoded viene restituito da `bodyParser.urlencoded({extended: false})`. Passa a `app.use()` la funzione restituita dalla precedente chiamata del metodo. Come al solito, il middleware deve essere montato prima di tutte le rotte che ne hanno bisogno.
Installa il modulo `body-parser` nel tuo `package.json`. Poi, richiedilo con `require` all'inizio del file. Memorizzalo in una variabile chiamata `bodyParser`. Il middleware per gestire i dati urlencoded viene restituito da `bodyParser.urlencoded({extended: false})`. Pass the function returned by the previous method call to `app.use()`. As usual, the middleware must be mounted before all the routes that depend on it.
**Nota:** `extended=false` è un'opzione di configurazione che dice al parser di usare la codifica classica. Quando lo si utilizza, i valori possono essere solo stringhe o array. La versione estesa consente una maggiore flessibilità dei dati, ma è superata da JSON.
**Note:** `extended` is a configuration option that tells `body-parser` which parsing needs to be used. When `extended=false` it uses the classic encoding `querystring` library. When `extended=true` it uses `qs` library for parsing.
When using `extended=false`, values can be only strings or arrays. The object returned when using `querystring` does not prototypically inherit from the default JavaScript `Object`, which means functions like `hasOwnProperty`, `toString` will not be available. The extended version allows more data flexibility, but it is outmatched by JSON.
# --hints--
Il middleware 'body-parser' dovrebbe essere montato
The 'body-parser' middleware should be mounted
```js
(getUserInput) =>

View File

@ -24,13 +24,13 @@ Infine, trasferisci tutte le rotte presenti nel tuo server e incollale nei nuovi
Continua ad aggiungere percorsi fino a quando non ci saranno più errori e il tuo file server non avrà più neanche una rotta (**ad eccezione della rotta nel blocco catch**)!
Now do the same thing in your auth.js file with all of the things related to authentication such as the serialization and the setting up of the local strategy and erase them from your server file. Be sure to add the dependencies in and call `auth(app, myDataBase)` in the server in the same spot.
Ora fai la stessa cosa nel tuo file auth.js con tutte le cose relative all'autenticazione come la serializzazione e l'impostazione della strategia locale e cancellali dal file del server. Assicurati di aggiungere le dipendenze e invocare `auth(app, myDataBase)` nel server nello stesso punto.
Submit your page when you think you've got it right. If you're running into errors, you can check out an example of the completed project [here](https://gist.github.com/camperbot/2d06ac5c7d850d8cf073d2c2c794cc92).
Invia la tua pagina quando pensi di averlo fatto correttamente. Se dovessi incontrare degli errori, puoi controllare il progetto completato [qui](https://gist.github.com/camperbot/2d06ac5c7d850d8cf073d2c2c794cc92).
# --hints--
Modules should be present.
Dovrebbero essere presenti dei moduli.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 589fc831f9fc0f352b528e75
title: Communicate by Emitting
title: Comunicare emettendo
challengeType: 2
forumTopicId: 301550
dashedName: communicate-by-emitting
@ -8,27 +8,27 @@ dashedName: communicate-by-emitting
# --description--
<dfn>Emit</dfn> is the most common way of communicating you will use. When you emit something from the server to 'io', you send an event's name and data to all the connected sockets. A good example of this concept would be emitting the current count of connected users each time a new user connects!
<dfn>Emit</dfn> è il modo più comune di comunicare che utilizzerai. Quando emetti qualcosa dal server a 'io', invii il nome e i dati di un evento a tutti i socket collegati. Un buon esempio di questo concetto sarebbe emettere il numero attuale di utenti connessi ogni volta che un nuovo utente si connette!
Start by adding a variable to keep track of the users, just before where you are currently listening for connections.
Inizia aggiungendo una variabile per tenere traccia degli utenti, poco prima di dove stai ascolta in attesa di connessioni.
```js
let currentUsers = 0;
```
Now, when someone connects, you should increment the count before emitting the count. So, you will want to add the incrementer within the connection listener.
Ora, quando qualcuno si connette, dovresti aumentare il conteggio prima di emetterlo. Quindi, vorrai aggiungere l'incrementatore all'interno del listener di connessione.
```js
++currentUsers;
```
Finally, after incrementing the count, you should emit the event (still within the connection listener). The event should be named 'user count', and the data should just be the `currentUsers`.
Infine, dopo aver incrementato il conteggio, dovresti emettere l'evento (sempre all'interno del listener di connessione). L'evento dovrebbe essere chiamato 'user count', e i dati dovrebbero essere solo `currentUsers` (utenti attuali).
```js
io.emit('user count', currentUsers);
```
Now, you can implement a way for your client to listen for this event! Similar to listening for a connection on the server, you will use the `on` keyword.
Ora, puoi fare in modo che il tuo client si metta in ascolto in attesa di questo evento! In modo simile ad attendere una connessione sul server, userai la parola chiave `on`.
```js
socket.on('user count', function(data) {
@ -36,13 +36,13 @@ socket.on('user count', function(data) {
});
```
Now, try loading up your app, authenticate, and you should see in your client console '1' representing the current user count! Try loading more clients up, and authenticating to see the number go up.
Ora, prova a caricare la tua app e a fare l'autenticazione: dovresti vedere nella tua console del client un '1' che rappresenta il numero attuale di utenti! Prova a caricare altri client, e autenticati in ognuno di essi per vedere il numero che aumenta.
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/28ef7f1078f56eb48c7b1aeea35ba1f5).
Invia la tua pagina quando pensi di averlo fatto correttamente. Se dovessi incontrare degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/28ef7f1078f56eb48c7b1aeea35ba1f5).
# --hints--
currentUsers should be defined.
currentUsers dovrebbe essere definito.
```js
(getUserInput) =>
@ -60,7 +60,7 @@ currentUsers should be defined.
);
```
Server should emit the current user count at each new connection.
Il server dovrebbe emettere il numero attuale di utenti per ogni nuova connessione.
```js
(getUserInput) =>
@ -78,7 +78,7 @@ Server should emit the current user count at each new connection.
);
```
Your client should be listening for 'user count' event.
Il tuo client dovrebbe ascoltare per eventi 'user count'.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 5895f70df9fc0f352b528e6a
title: Create New Middleware
title: Creare un nuovo middleware
challengeType: 2
forumTopicId: 301551
dashedName: create-new-middleware
@ -8,9 +8,9 @@ dashedName: create-new-middleware
# --description--
As is, any user can just go to `/profile` whether they have authenticated or not, by typing in the url. We want to prevent this, by checking if the user is authenticated first before rendering the profile page. This is the perfect example of when to create a middleware.
Attualmente, ogni utente può andare a `/profile` indipendentemente dal fatto che sia autenticato o meno, semplicemente digitando l'url. Vogliamo evitarlo, controllando che l'utente sia autenticato prima di visualizzare la pagina del profilo. Questo è l'esempio perfetto di quando conviene creare un middleware.
The challenge here is creating the middleware function `ensureAuthenticated(req, res, next)`, which will check if a user is authenticated by calling passport's `isAuthenticated` method on the `request` which, in turn, checks if `req.user` is defined. If it is, then `next()` should be called, otherwise, we can just respond to the request with a redirect to our homepage to login. An implementation of this middleware is:
La sfida consiste nel creare la funzione middleware `ensureAuthenticated(req, res, next)`, che controlla se un utente è autenticato o meno invocando il metodo `isAuthenticated` di passport su `request`, e questo a sua volta controlla se `req.user` è definito. Se lo è, allora `next()` dovrebbe essere invocato, altrimenti, possiamo rispondere alla richiesta con un reindirizzamento alla homepage per fare l'autenticazione. Una implementazione di questo middleware è:
```js
function ensureAuthenticated(req, res, next) {
@ -21,7 +21,7 @@ function ensureAuthenticated(req, res, next) {
};
```
Now add *ensureAuthenticated* as a middleware to the request for the profile page before the argument to the get request containing the function that renders the page.
Ora aggiungi *ensureAuthenticated* come middleware alla richiesta per la pagina del profilo prima dell'argomento della richiesta GET che contiene la funzione che visualizza la pagina.
```js
app
@ -31,11 +31,11 @@ app
});
```
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/ae49b8778cab87e93284a91343da0959).
Invia la tua pagina quando pensi di averlo fatto correttamente. Se dovessi incontrare degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/ae49b8778cab87e93284a91343da0959).
# --hints--
Middleware ensureAuthenticated should be implemented and on our /profile route.
Il middleware ensureAuthenticated dovrebbe essere inplementato sulla rotta /profile.
```js
(getUserInput) =>
@ -58,7 +58,7 @@ Middleware ensureAuthenticated should be implemented and on our /profile route.
);
```
A Get request to /profile should correctly redirect to / since we are not authenticated.
Una richiesta Get a /profile dovrebbe reindirizzare a / visto che non siamo autenticati.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 589fc831f9fc0f352b528e76
title: Handle a Disconnect
title: Gestire una disconnessione
challengeType: 2
forumTopicId: 301552
dashedName: handle-a-disconnect
@ -8,9 +8,9 @@ dashedName: handle-a-disconnect
# --description--
You may notice that up to now you have only been increasing the user count. Handling a user disconnecting is just as easy as handling the initial connect, except you have to listen for it on each socket instead of on the whole server.
Potresti notare che fino a questo momento hai solo incremementato il numero degli utenti. Gestire la disconnessione di un utente è semplice come gestire la connessione iniziale, solo che si deve mettersi in ascolto per essa su ogni socket invece che su tutto il server.
To do this, add another listener inside the existing `'connect'` listener that listens for `'disconnect'` on the socket with no data passed through. You can test this functionality by just logging that a user has disconnected to the console.
Per fare questo, aggiungi un altro listener all'interno del listener `'connect'` esistente, in modo che attenda un evento `'disconnect'` sul socket (senza alcun passaggio di dati). È possibile testare questa funzionalità semplicemente scrivendo nella console che un utente si è disconnesso.
```js
socket.on('disconnect', () => {
@ -18,15 +18,15 @@ socket.on('disconnect', () => {
});
```
To make sure clients continuously have the updated count of current users, you should decrease the currentUsers by 1 when the disconnect happens then emit the 'user count' event with the updated count!
Per assicurarti che i client continuino ad avere il numero aggiornato degli utenti connessi, quando avviene una disconnessione dovresti diminuire currentUsers di 1 e emettere l'evento 'user count' con il conteggio aggiornato!
**Note:** Just like `'disconnect'`, all other events that a socket can emit to the server should be handled within the connecting listener where we have 'socket' defined.
**Nota:** Proprio come `'disconnect'`, tutti gli altri eventi che un socket può emettere sul server devono essere gestiti all'interno del listener di connessione dove abbiamo definito 'socket'.
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/ab1007b76069884fb45b215d3c4496fa).
Invia la tua pagina quando pensi di averlo fatto correttamente. Se dovessi incontrare degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/ab1007b76069884fb45b215d3c4496fa).
# --hints--
Server should handle the event disconnect from a socket.
Il server deve gestire l'evento di disconnessione da un socket.
```js
(getUserInput) =>
@ -40,7 +40,7 @@ Server should handle the event disconnect from a socket.
);
```
Your client should be listening for 'user count' event.
Il tuo client dovrebbe essere in ascolto per eventi di tipo 'user count'.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 58a25c98f9fc0f352b528e7f
title: Hashing Your Passwords
title: Hashing delle password
challengeType: 2
forumTopicId: 301553
dashedName: hashing-your-passwords
@ -8,13 +8,13 @@ dashedName: hashing-your-passwords
# --description--
Going back to the information security section, you may remember that storing plaintext passwords is *never* okay. Now it is time to implement BCrypt to solve this issue.
Tornando alla sezione sulla sicurezza delle informazioni, potresti ricordare che memorizzare le password non è *mai* una buona cosa. Ora è tempo di implementare BCrypt per risolvere questo problema.
Add `bcrypt@~5.0.0` as a dependency, and require it in your server. You will need to handle hashing in 2 key areas: where you handle registering/saving a new account, and when you check to see that a password is correct on login.
Aggiungi `bcrypt@~5.0.0` come dipendenza, e richiedilo nel tuo server. Dovrai gestire l'hashing in 2 aree chiave: dove gestisci la registrazione/salvataggio di un nuovo account, e quando controlli per vedere se una password è corretta al momento dell'accesso.
Currently on our registration route, you insert a user's password into the database like so: `password: req.body.password`. An easy way to implement saving a hash instead is to add the following before your database logic `const hash = bcrypt.hashSync(req.body.password, 12);`, and replacing the `req.body.password` in the database saving with just `password: hash`.
Attualmente sul nostro percorso di registrazione, inserisci la password di un utente nel database in questo modo: `password: req.body.password`. Un modo semplice per implementare il salvataggio di un hash invece è quello di aggiungere quanto segue prima della logica del database `const hash = bcrypt.hashSync(req.body.password, 12);`, e sostituire `req.body.password` nel database salvando solo `password: hash`.
Finally, on our authentication strategy, we check for the following in our code before completing the process: `if (password !== user.password) { return done(null, false); }`. After making the previous changes, now `user.password` is a hash. Before making a change to the existing code, notice how the statement is checking if the password is **not** equal then return non-authenticated. With this in mind, your code could look as follows to properly check the password entered against the hash:
Infine, nella nostra strategia di autenticazione, controlliamo quanto segue nel nostro codice prima di completare il processo: `if (password !== user.password) { return done(null, false); }`. Dopo aver apportato le modifiche precedenti, `user.password` è diventato un hash. Prima di apportare una modifica al codice esistente, nota come la dichiarazione verifica se la password è **non** uguale, quindi restituisce not-authenticated. Con questo in mente, il codice potrebbe apparire come segue in modo da confrontare correttamente la password inserita con l'hash:
```js
if (!bcrypt.compareSync(password, user.password)) {
@ -22,13 +22,13 @@ if (!bcrypt.compareSync(password, user.password)) {
}
```
That is all it takes to implement one of the most important security features when you have to store passwords!
Questo è tutto quello che serve per implementare una delle caratteristiche di sicurezza più importanti quando si devono memorizzare le password!
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/dc16cca09daea4d4151a9c36a1fab564).
Invia la tua pagina quando pensi di averlo fatto correttamente. Se incontri degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/dc16cca09daea4d4151a9c36a1fab564).
# --hints--
BCrypt should be a dependency.
BCrypt dovrebbe essere una dipendenza.
```js
(getUserInput) =>
@ -47,7 +47,7 @@ BCrypt should be a dependency.
);
```
BCrypt should be correctly required and implemented.
BCrypt dovrebbe essere correttamente richiesto e implementato.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 5895f70df9fc0f352b528e69
title: How to Use Passport Strategies
title: Usare le strategie passport
challengeType: 2
forumTopicId: 301555
dashedName: how-to-use-passport-strategies
@ -8,21 +8,21 @@ dashedName: how-to-use-passport-strategies
# --description--
In the `index.pug` file supplied, there is actually a login form. It has previously been hidden because of the inline JavaScript `if showLogin` with the form indented after it. Before `showLogin` as a variable was never defined, so it never rendered the code block containing the form. Go ahead and on the `res.render` for that page add a new variable to the object `showLogin: true`. When you refresh your page, you should then see the form! This form is set up to **POST** on `/login`, so this is where we should set up to accept the POST and authenticate the user.
Nel file `index.pug` fornito, c'è in realtà un modulo di login. In precedenza è stato nascosto a causa del JavaScript in linea `if showLogin` con il modulo indentato dopo di esso. `showLogin` non è mai stato definito come variabile in precedenza, quindi non ha mai presentato il blocco di codice contenente il modulo. Vai avanti e nel `res.render` per quella pagina aggiungi una nuova variabile all'oggetto `showLogin: true`. Quando aggiorni la pagina, dovresti vedere il modulo! Questo modulo è impostato per fare una richiesta **POST** su `/login`, quindi qui è dove dovremmo mettere il codice per accettare il POST e autenticare l'utente.
For this challenge you should add the route `/login` to accept a POST request. To authenticate on this route, you need to add a middleware to do so before then sending a response. This is done by just passing another argument with the middleware before your `function(req,res)` with your response! The middleware to use is `passport.authenticate('local')`.
Per questa sfida dovresti aggiungere la rotta `/login` per accettare una richiesta POST. Per autenticarsi su questo percorso, è necessario aggiungere un middleware per farlo prima di inviare una risposta. Questo viene fatto semplicemente passando un altro argomento con il middleware prima della tua `function(req,res)` con la tua risposta! Il middleware da usare è `passport.authenticate('local')`.
`passport.authenticate` can also take some options as an argument such as: `{ failureRedirect: '/' }` which is incredibly useful, so be sure to add that in as well. The response after using the middleware (which will only be called if the authentication middleware passes) should be to redirect the user to `/profile` and that route should render the view `profile.pug`.
`passport.authenticate` può anche prendere alcune opzioni come un argomento tipo: `{ failureRedirect: '/' }` che è incredibilmente utile, quindi assicurati di aggiungere anche quello. La risposta dopo aver utilizzato il middleware (che verrà chiamato solo se l'autenticazione middleware ha successo) dovrebbe essere quella di reindirizzare l'utente a `/profile` e tale percorso dovrebbe presentare la vista `profile.pug`.
If the authentication was successful, the user object will be saved in `req.user`.
Se l'autenticazione è riuscita, l'oggetto utente verrà salvato in `req.user`.
At this point, if you enter a username and password in the form, it should redirect to the home page `/`, and the console of your server should display `'User {USERNAME} attempted to log in.'`, since we currently cannot login a user who isn't registered.
A questo punto, se inserisci un nome utente e una password nel modulo, esso dovrebbe reindirizzare alla home page `/`, e la console del tuo server dovrebbe mostrare `'User {USERNAME} attempted to log in.'`, dato che al momento non possiamo effettuare il login di un utente che non è registrato.
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/7ad011ac54612ad53188b500c5e99cb9).
Invia la tua pagina quando pensi di averlo fatto correttamente. Se dovessi incontrare degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/7ad011ac54612ad53188b500c5e99cb9).
# --hints--
All steps should be correctly implemented in the server.js.
Tutti i passaggi dovrebbero essere correttamente implementati nel server.js.
```js
(getUserInput) =>
@ -50,7 +50,7 @@ All steps should be correctly implemented in the server.js.
);
```
A POST request to /login should correctly redirect to /.
Una richiesta POST a /login dovrebbe reindirizzare correttamente a /.
```js
(getUserInput) =>

View File

@ -1,6 +1,6 @@
---
id: 589fc830f9fc0f352b528e74
title: Set up the Environment
title: Configurare l'ambiente
challengeType: 2
forumTopicId: 301566
dashedName: set-up-the-environment
@ -8,20 +8,20 @@ dashedName: set-up-the-environment
# --description--
The following challenges will make use of the `chat.pug` file. So, in your `routes.js` file, add a GET route pointing to `/chat` which makes use of `ensureAuthenticated`, and renders `chat.pug`, with `{ user: req.user }` passed as an argument to the response. Now, alter your existing `/auth/github/callback` route to set the `req.session.user_id = req.user.id`, and redirect to `/chat`.
Le seguenti sfide utilizzeranno il file `chat.pug`. Così, nel tuo file `routes.js`, aggiugi una rotta GET che punta a `/chat` che fa uso di `ensureAuthenticated`, e fa il rendering di `chat.pug`, con `{ user: req.user }` passato come argomento alla risposta. Adesso, modifica la rotta esistente `/auth/github/callback` per impostare il `req.session.user_id = req.user.id` e reindirizzare a `/chat`.
Add `socket.io@~2.3.0` as a dependency and require/instantiate it in your server defined as follows, with `http` (comes built-in with Nodejs):
Aggiungi `socket.io@~2.3.0` come dipendenza e richiedila/instanziala nel server definito come segue, con `http` (che è già integrato in Nodejs):
```javascript
const http = require('http').createServer(app);
const io = require('socket.io')(http);
```
Now that the *http* server is mounted on the *express app*, you need to listen from the *http* server. Change the line with `app.listen` to `http.listen`.
Ora che il server *http* è montato sull'app *express*, devi rimanere in ascolto dal server *http*. Cambia la riga con `app.listen` a `http.listen`.
The first thing needing to be handled is listening for a new connection from the client. The <dfn>on</dfn> keyword does just that- listen for a specific event. It requires 2 arguments: a string containing the title of the event that's emitted, and a function with which the data is passed though. In the case of our connection listener, we use *socket* to define the data in the second argument. A socket is an individual client who is connected.
La prima cosa che deve essere gestita è l'ascolto di una nuova connessione dal client. La parola chiave <dfn>on</dfn> fa proprio questo: ascolta un evento specifico. Richiede 2 argomenti: una stringa contenente il titolo dell'evento emesso, e una funzione con cui i dati vengono trasmessi. Nel caso del nostro listener di connessione, usiamo *socket* per definire i dati nel secondo argomento. Un socket è un singolo client che è connesso.
To listen for connections to your server, add the following within your database connection:
Per rimanere in ascolto di connessioni al server, aggiungi quanto segue nella connessione al database:
```javascript
io.on('connection', socket => {
@ -29,24 +29,24 @@ io.on('connection', socket => {
});
```
Now for the client to connect, you just need to add the following to your `client.js` which is loaded by the page after you've authenticated:
Ora affinché il client si connetta, devi solo aggiungere quanto segue al tuo `client.js` che viene caricato dalla pagina dopo l'autenticazione:
```js
/*global io*/
let socket = io();
```
The comment suppresses the error you would normally see since 'io' is not defined in the file. We've already added a reliable CDN to the Socket.IO library on the page in chat.pug.
Il commento sopprime l'errore che normalmente vedresti poiché 'io' non è definito nel file. Abbiamo già aggiunto una CDN affidabile alla libreria Socket.IO sulla pagina in chat.pug.
Now try loading up your app and authenticate and you should see in your server console 'A user has connected'!
Ora prova a caricare la tua app e ad autenticarti: dovresti vedere nella console del tuo server 'A user has connected'!
**Note:**`io()` works only when connecting to a socket hosted on the same url/server. For connecting to an external socket hosted elsewhere, you would use `io.connect('URL');`.
**Nota:**`io()` funziona solo quando ci si connette a un socket ospitato sullo stesso url/server. Per connettersi ad un socket esterno ospitato altrove, si utilizzerebbe `io.connect('URL');`.
Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/aae41cf59debc1a4755c9a00ee3859d1).
Invia la tua pagina quando pensi di averlo fatto correttamente. Se dovessi incontrare degli errori, puoi controllare il progetto completato fino a questo punto [qui](https://gist.github.com/camperbot/aae41cf59debc1a4755c9a00ee3859d1).
# --hints--
`socket.io` should be a dependency.
`socket.io` dovrebbe essere una dipendenza.
```js
(getUserInput) =>
@ -65,7 +65,7 @@ Submit your page when you think you've got it right. If you're running into erro
);
```
You should correctly require and instantiate `http` as `http`.
Dovresti richiedere e instanziare correttamente `http` come `http`.
```js
(getUserInput) =>
@ -83,7 +83,7 @@ You should correctly require and instantiate `http` as `http`.
);
```
You should correctly require and instantiate `socket.io` as `io`.
Dovresti richiedere e instanziare correttamente `socket.io` come `io`.
```js
(getUserInput) =>
@ -101,7 +101,7 @@ You should correctly require and instantiate `socket.io` as `io`.
);
```
Socket.IO should be listening for connections.
Socket.IO dovrebbe stare in ascolto di connessioni.
```js
(getUserInput) =>
@ -119,7 +119,7 @@ Socket.IO should be listening for connections.
);
```
Your client should connect to your server.
Il tuo client dovrebbe connettersi al tuo server.
```js
(getUserInput) =>

View File

@ -11,7 +11,7 @@ dashedName: create-decimal-numbers-with-javascript
Nós também podemos armazenar números decimais em variáveis. Números decimais são referidos as vezes como números de <dfn>ponto flutuante</dfn> ou <dfn>floats</dfn>.
**Nota:** Nem todos os números reais podem ser representados com precisão no <dfn>ponto flutuante</dfn>. Isso pode levar a erros de arredondamento. [Detalhes aqui](https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems).
**Nota:** Nem todos os números reais podem ser representados com precisão no <dfn>ponto flutuante</dfn>. Isso pode levar a erros de arredondamento. [Detalhes aqui](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems).
# --instructions--

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ac
title: Increment a Number with JavaScript
title: Incremente um Número com JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8GLT9'
forumTopicId: 18201
@ -9,33 +9,33 @@ dashedName: increment-a-number-with-javascript
# --description--
You can easily <dfn>increment</dfn> or add one to a variable with the `++` operator.
Você pode facilmente <dfn>incrementar</dfn> ou adicionar 1 à variável com o operador `++`.
```js
i++;
```
is the equivalent of
é o equivalente a
```js
i = i + 1;
```
**Note:** The entire line becomes `i++;`, eliminating the need for the equal sign.
**Nota:** A linha inteira se torna `i++;`, eliminando a necessidade do sinal de igual.
# --instructions--
Change the code to use the `++` operator on `myVar`.
Modifique o código usando o operador `++` em `myVar`.
# --hints--
`myVar` should equal `88`.
`myVar` deve ser igual a `88`.
```js
assert(myVar === 88);
```
You should not use the assignment operator.
Você não deve usar o operador de atribuição.
```js
assert(
@ -43,13 +43,13 @@ assert(
);
```
You should use the `++` operator.
Você deve usar o operador `++`.
```js
assert(/[+]{2}\s*myVar|myVar\s*[+]{2}/.test(code));
```
You should not change code above the specified comment.
Você não deve alterar o código acima do comentário especificado.
```js
assert(/var myVar = 87;/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244a9
title: Initializing Variables with the Assignment Operator
title: Inicializando Variáveis com o Operador de Atribuição
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWJ4Bfb'
forumTopicId: 301171
@ -9,21 +9,21 @@ dashedName: initializing-variables-with-the-assignment-operator
# --description--
It is common to <dfn>initialize</dfn> a variable to an initial value in the same line as it is declared.
É comum <dfn>inicializar</dfn> a variável com um valor inicial na mesma linha que declarada.
```js
var myVar = 0;
```
Creates a new variable called `myVar` and assigns it an initial value of `0`.
Cria uma nova variável chamada `myVar` e atribui o seu valor inicial como `0`.
# --instructions--
Define a variable `a` with `var` and initialize it to a value of `9`.
Define uma variável `a` com `var` e a inicializa com o valor de `9`.
# --hints--
You should initialize `a` to a value of `9`.
Você deve inicializar `a` para o valor de `9`.
```js
assert(/var\s+a\s*=\s*9(\s*;?\s*)$/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244db
title: Introducing Else If Statements
title: Introduzindo Instruções Else If
challengeType: 1
videoUrl: 'https://scrimba.com/c/caeJ2hm'
forumTopicId: 18206
@ -9,7 +9,7 @@ dashedName: introducing-else-if-statements
# --description--
If you have multiple conditions that need to be addressed, you can chain `if` statements together with `else if` statements.
Se você tem múltiplas condições que precisam ser resolvidas, você pode encadear as instruções `if` junto com instruções `else if`.
```js
if (num > 15) {
@ -23,23 +23,23 @@ if (num > 15) {
# --instructions--
Convert the logic to use `else if` statements.
Converta a lógica para usar instruções `else if`.
# --hints--
You should have at least two `else` statements
Você deve ter pelo menos duas instruções `else`
```js
assert(code.match(/else/g).length > 1);
```
You should have at least two `if` statements
Você deve ter pelo menos duas instruções `if`
```js
assert(code.match(/if/g).length > 1);
```
You should have closing and opening curly braces for each `if else` code block.
Você deve ter chaves de abertura e fechamento para cada bloco de código de `if else`.
```js
assert(
@ -49,31 +49,31 @@ assert(
);
```
`testElseIf(0)` should return the string `Smaller than 5`
`testElseIf(0)` deve retornar a string `Smaller than 5`
```js
assert(testElseIf(0) === 'Smaller than 5');
```
`testElseIf(5)` should return the string `Between 5 and 10`
`testElseIf(5)` deve retornar a string `Between 5 and 10`
```js
assert(testElseIf(5) === 'Between 5 and 10');
```
`testElseIf(7)` should return the string `Between 5 and 10`
`testElseIf(7)` deve retornar a string `Between 5 and 10`
```js
assert(testElseIf(7) === 'Between 5 and 10');
```
`testElseIf(10)` should return the string `Between 5 and 10`
`testElseIf(10)` deve retornar a string `Between 5 and 10`
```js
assert(testElseIf(10) === 'Between 5 and 10');
```
`testElseIf(12)` should return the string `Greater than 10`
`testElseIf(12)` deve retornar a string `Greater than 10`
```js
assert(testElseIf(12) === 'Greater than 10');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244da
title: Introducing Else Statements
title: Introduzindo Instruções Else
challengeType: 1
videoUrl: 'https://scrimba.com/c/cek4Efq'
forumTopicId: 18207
@ -9,7 +9,7 @@ dashedName: introducing-else-statements
# --description--
When a condition for an `if` statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen. With an `else` statement, an alternate block of code can be executed.
Quando uma condição para uma instrução `if` for verdadeiro, o bloco de código seguinte será executado. E quando a condição for falsa? Normalmente nada aconteceria. Com uma instrução `else`, um bloco de código alternativo pode ser executado.
```js
if (num > 10) {
@ -21,47 +21,47 @@ if (num > 10) {
# --instructions--
Combine the `if` statements into a single `if/else` statement.
Combine as instruções `if` em uma única instrução `if/else`.
# --hints--
You should only have one `if` statement in the editor
Você deve ter apenas uma instrução `if` no editor
```js
assert(code.match(/if/g).length === 1);
```
You should use an `else` statement
Você deve usar uma instrução `else`
```js
assert(/else/g.test(code));
```
`testElse(4)` should return the string `5 or Smaller`
`testElse(4)` deve retornar a string `5 or Smaller`
```js
assert(testElse(4) === '5 or Smaller');
```
`testElse(5)` should return the string `5 or Smaller`
`testElse(5)` deve retornar a string `5 or Smaller`
```js
assert(testElse(5) === '5 or Smaller');
```
`testElse(6)` should return the string `Bigger than 5`
`testElse(6)` deve retornar a string `Bigger than 5`
```js
assert(testElse(6) === 'Bigger than 5');
```
`testElse(10)` should return the string `Bigger than 5`
`testElse(10)` deve retornar a string `Bigger than 5`
```js
assert(testElse(10) === 'Bigger than 5');
```
You should not change the code above or below the specified comments.
Você não deve alterar o código acima ou abaixo dos comentários especificados.
```js
assert(/var result = "";/.test(code) && /return result;/.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56104e9e514f539506016a5c
title: Iterate Odd Numbers With a For Loop
title: Itere Números Ímpares Com um Laço For
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm8n7T9'
forumTopicId: 18212
@ -9,9 +9,9 @@ dashedName: iterate-odd-numbers-with-a-for-loop
# --description--
For loops don't have to iterate one at a time. By changing our `final-expression`, we can count by even numbers.
Laços for não tem de iterar um de cada vez. Ao alterar nossa `expressão final`, nós podemos contar os números pares.
We'll start at `i = 0` and loop while `i < 10`. We'll increment `i` by 2 each loop with `i += 2`.
Começaremos em `i = 0` e um laço while `i < 10`. Incrementaremos `i` em 2 a cada iteração com `i += 2`.
```js
var ourArray = [];
@ -20,21 +20,21 @@ for (var i = 0; i < 10; i += 2) {
}
```
`ourArray` will now contain `[0,2,4,6,8]`. Let's change our `initialization` so we can count by odd numbers.
`ourArray` agora conterá `[0,2,4,6,8]`. Vamos mudar nossa `inicialização` para que possamos contar por números ímpares.
# --instructions--
Push the odd numbers from 1 through 9 to `myArray` using a `for` loop.
Adicione (push) os números ímpares de 9 até 1 para `myArray` usando um laço `for`.
# --hints--
You should be using a `for` loop for this.
Você deve estar usando um laço `for` para isso.
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
`myArray` should equal `[1,3,5,7,9]`.
`myArray` deve ser igual a `[1,3,5,7,9]`.
```js
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);

View File

@ -1,6 +1,6 @@
---
id: 5675e877dbd60be8ad28edc6
title: Iterate Through an Array with a For Loop
title: Itere através de um Array com Laço For
challengeType: 1
videoUrl: 'https://scrimba.com/c/caeR3HB'
forumTopicId: 18216
@ -9,7 +9,7 @@ dashedName: iterate-through-an-array-with-a-for-loop
# --description--
A common task in JavaScript is to iterate through the contents of an array. One way to do that is with a `for` loop. This code will output each element of the array `arr` to the console:
Uma tarefa comum em JavaScript é para iterar através do conteúdo de um array. Uma forma de fazer isso é com um laço `for`. Esse código irá exibir cada elemento do array `arr` no console:
```js
var arr = [10, 9, 8, 7, 6];
@ -18,33 +18,33 @@ for (var i = 0; i < arr.length; i++) {
}
```
Remember that arrays have zero-based indexing, which means the last index of the array is `length - 1`. Our condition for this loop is `i < arr.length`, which stops the loop when `i` is equal to `length`. In this case the last iteration is `i === 4` i.e. when `i` becomes equal to `arr.length - 1` and outputs `6` to the console. Then `i` increases to `5`, and the loop terminates because `i < arr.length` is `false`.
Lembre-se de que arrays têm indexação baseada em zero, o que significa que o último índice do array é de `length - 1`. Nossa condição para esse laço é `i < arr.length`, a qual interrompe o laço quando `i` é igual a `length`. Nesse caso a última iteração é ` i === 4` i.e. quando `i` se tornar igual a `arr.length - 1` e exibe `6` no console. Em seguida, `i` aumenta para `5`, e o laço é interrompido porque `i < arr.length` é `false`.
# --instructions--
Declare and initialize a variable `total` to `0`. Use a `for` loop to add the value of each element of the `myArr` array to `total`.
Declare e inicialize uma variável `total` como `0`. Use um laço `for` para adicionar o valor de cada elemento do array `myArr` para `total`.
# --hints--
`total` should be declared and initialized to 0.
`total` deve ser declarado e inicializado como 0.
```js
assert(code.match(/(var|let|const)\s*?total\s*=\s*0.*?;?/));
```
`total` should equal 20.
`total` deve ser igual a 20.
```js
assert(total === 20);
```
You should use a `for` loop to iterate through `myArr`.
Você deve usar um laço `for` para iterar através de `myArr`.
```js
assert(/for\s*\(/g.test(code) && /myArr\s*\[/g.test(code));
```
You should not attempt to directly assign the value 20 to `total`.
Você não deve tentar atribuir diretamente o valor 20 para `total`.
```js
assert(!__helpers.removeWhiteSpace(code).match(/total[=+-]0*[1-9]+/gm));

View File

@ -1,6 +1,6 @@
---
id: 5a2efd662fb457916e1fe604
title: Iterate with JavaScript Do...While Loops
title: Itere com Laços Do...While JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqWGcp'
forumTopicId: 301172
@ -9,7 +9,7 @@ dashedName: iterate-with-javascript-do---while-loops
# --description--
The next type of loop you will learn is called a `do...while` loop. It is called a `do...while` loop because it will first `do` one pass of the code inside the loop no matter what, and then continue to run the loop `while` the specified condition evaluates to `true`.
O próximo tipo de laço que você aprenderá é chamado de laço `do...while`. É chamado um laço `do...while` porque primeiro irá toda vez `fazer (do)`, ou executar, uma vez o bloco de código após a instrução do, não importa o que acontecer, e então continuará a executar o laço `enquanto (while)` a condição for `true`.
```js
var ourArray = [];
@ -20,7 +20,7 @@ do {
} while (i < 5);
```
The example above behaves similar to other types of loops, and the resulting array will look like `[0, 1, 2, 3, 4]`. However, what makes the `do...while` different from other loops is how it behaves when the condition fails on the first check. Let's see this in action: Here is a regular `while` loop that will run the code in the loop as long as `i < 5`:
O exemplo acima se comporta de forma similar a outros tipos de laços, e o array resultante se parecerá com `[0,1,2,3,4]`. No entanto, o que torna o laço `do...while` diferente de outros laços é como ele se comporta quando uma condição falha na primeira verificação. Vamos ver isso na prática: Aqui está um laço comum `while` que rodará o código no laço enquanto `i < 5`:
```js
var ourArray = [];
@ -31,7 +31,7 @@ while (i < 5) {
}
```
In this example, we initialize the value of `ourArray` to an empty array and the value of `i` to 5. When we execute the `while` loop, the condition evaluates to `false` because `i` is not less than 5, so we do not execute the code inside the loop. The result is that `ourArray` will end up with no values added to it, and it will still look like `[]` when all of the code in the example above has completed running. Now, take a look at a `do...while` loop:
Nesse exemplo, inicializamos o valor de `ourArray` como um array vazio e o valor de `i` sendo 5. Quando executamos o laço `while`, a condição é igual a `false` porque `i` não é menor que 5, portanto nós não executamos o código dentro do laço. O resultado é que `ourArray` terminará sem valores adicionados a ele, e ainda se parecerá com `[]` quando todas as linhas do código no exemplo acima for completamente executadas. Agora, dê uma olhada no laço `do...while`:
```js
var ourArray = [];
@ -42,27 +42,27 @@ do {
} while (i < 5);
```
In this case, we initialize the value of `i` to 5, just like we did with the `while` loop. When we get to the next line, there is no condition to evaluate, so we go to the code inside the curly braces and execute it. We will add a single element to the array and then increment `i` before we get to the condition check. When we finally evaluate the condition `i < 5` on the last line, we see that `i` is now 6, which fails the conditional check, so we exit the loop and are done. At the end of the above example, the value of `ourArray` is `[5]`. Essentially, a `do...while` loop ensures that the code inside the loop will run at least once. Let's try getting a `do...while` loop to work by pushing values to an array.
Nesse caso, nós inicializamos o valor de `i` para 5, assim como fizemos com o laço `while`. Quando chegamos na próxima linha, não há condição a ser analisada, então nós vamos ao código dentro das chaves e o executamos. Nós adicionaremos um único elemento ao array e então incrementamos `i` antes de chegarmos a verificação da condição. Quando nós finalmente temos o resultado da condição `i < 5` na última linha, nós notamos que `i` agora é 6, o que não cumpre a verificação da condição, então nós saímos do laço e terminamos. Ao final do exemplo acima, o valor de `ourArray` é `[5]`. Essencialmente, um laço `do...while` garante que o código dentro do laço será executado pelo menos uma vez. Vamos tentar fazer um laço `do...while` funcionar empurrando valores para um array.
# --instructions--
Change the `while` loop in the code to a `do...while` loop so the loop will push only the number `10` to `myArray`, and `i` will be equal to `11` when your code has finished running.
Altere o laço `while` no código para um laço `do...while` para que o laço adicione apenas o número `10` no `myArray` e `i` será igual a `11` quando seu código terminar de rodar.
# --hints--
You should be using a `do...while` loop for this exercise.
Você deve usar um laço `do...while` nesse exercício.
```js
assert(code.match(/do/g));
```
`myArray` should equal `[10]`.
`myArray` deve ser igual a `[10]`.
```js
assert.deepEqual(myArray, [10]);
```
`i` should equal `11`
`i` deve ser igual a `11`
```js
assert.equal(i, 11);

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb5bdef
title: Iterate with JavaScript For Loops
title: Itere com Laços For JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yNVCe'
forumTopicId: 18219
@ -9,21 +9,21 @@ dashedName: iterate-with-javascript-for-loops
# --description--
You can run the same code multiple times by using a loop.
Você pode rodar o mesmo código várias vezes usando um laço.
The most common type of JavaScript loop is called a `for` loop because it runs for a specific number of times.
O tipo mais comum de laço JavaScript é chamado de laço `for` porque ele é executado por um número especificado de vezes.
For loops are declared with three optional expressions separated by semicolons:
Laços For são declarados com três expressões opcionais separadas por ponto e vírgula:
`for (a; b; c)`, where `a` is the intialization statement, `b` is the condition statement, and `c` is the final expression.
`for (a; b; c)`, onde `a` é a declaração de inicialização, `b` é a declaração de condição, e `c` é a expressão final.
The initialization statement is executed one time only before the loop starts. It is typically used to define and setup your loop variable.
A declaração de inicialização é executada apenas uma vez antes do laço iniciar. Normalmente é usado para definir e configurar sua variável de laço.
The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to `true`. When the condition is `false` at the start of the iteration, the loop will stop executing. This means if the condition starts as false, your loop will never execute.
A declaração de condição é verificada no início de cada iteração do laço e irá continuar enquanto seu valor for `true`. Quando a condição for `false` no início da iteração, o laço irá parar de executar. Isso significa que se a condição de início for falsa, seu laço nunca será executado.
The final expression is executed at the end of each loop iteration, prior to the next condition check and is usually used to increment or decrement your loop counter.
A expressão final é executada no final de cada iteração do laço, antes da verificação da próxima condição e normalmente é usada para incrementar ou decrementar o contador do laço.
In the following example we initialize with `i = 0` and iterate while our condition `i < 5` is true. We'll increment `i` by `1` in each loop iteration with `i++` as our final expression.
No exemplo a seguir, inicializamos com `i = 0` e iteramos enquanto nossa condição `i < 5` for verdadeira. Nós incrementaremos `i` em `1` em cada iteração do laço com `i++` como nossa expressão final.
```js
var ourArray = [];
@ -32,21 +32,21 @@ for (var i = 0; i < 5; i++) {
}
```
`ourArray` will now have the value `[0,1,2,3,4]`.
`ourArray` agora terá o valor de `[0,1,2,3,4]`.
# --instructions--
Use a `for` loop to push the values 1 through 5 onto `myArray`.
Use o laço `for` para adicionar os valores de 1 até 5 dentro de `myArray`.
# --hints--
You should be using a `for` loop for this.
Você deve usar um laço `for` para isso.
```js
assert(/for\s*\([^)]+?\)/.test(code));
```
`myArray` should equal `[1,2,3,4,5]`.
`myArray` deve ser igual a `[1,2,3,4,5]`.
```js
assert.deepEqual(myArray, [1, 2, 3, 4, 5]);

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb1bdef
title: Iterate with JavaScript While Loops
title: Itere com Laços While em JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/c8QbnCM'
forumTopicId: 18220
@ -9,9 +9,9 @@ dashedName: iterate-with-javascript-while-loops
# --description--
You can run the same code multiple times by using a loop.
Você pode rodar o mesmo código várias vezes ao usar um laço.
The first type of loop we will learn is called a `while` loop because it runs while a specified condition is true and stops once that condition is no longer true.
O primeiro tipo de laço que aprenderemos é chamado de laço `while` porque ele irá rodar enquanto uma condição específica for verdadeira e irá parar uma vez que a condição não for mais verdadeira.
```js
var ourArray = [];
@ -22,23 +22,23 @@ while(i < 5) {
}
```
In the code example above, the `while` loop will execute 5 times and append the numbers 0 through 4 to `ourArray`.
No código de exemplo acima, o laço `while` executará por 5 vezes e adicionará os números de 0 até 4 ao `ourArray`.
Let's try getting a while loop to work by pushing values to an array.
Vamos tentar fazer um laço while funcionar empurrando valores para um array.
# --instructions--
Add the numbers 5 through 0 (inclusive) in descending order to `myArray` using a `while` loop.
Adicione os números de 5 até 1 (inclusivo) em ordem descendente para `myArray` usando um laço `while`.
# --hints--
You should be using a `while` loop for this.
Você deve usar um laço `while` para isso.
```js
assert(code.match(/while/g));
```
`myArray` should equal `[5,4,3,2,1,0]`.
`myArray` deve ser igual a `[5,4,3,2,1,0]`.
```js
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244bf
title: Local Scope and Functions
title: Escopo Local e Funções
challengeType: 1
videoUrl: 'https://scrimba.com/c/cd62NhM'
forumTopicId: 18227
@ -9,9 +9,9 @@ dashedName: local-scope-and-functions
# --description--
Variables which are declared within a function, as well as the function parameters, have <dfn>local</dfn> scope. That means they are only visible within that function.
Variáveis que são declaradas dentro de uma função, assim como parâmetros de funções, possuem escopo <dfn>local</dfn>. Isso significa que eles são visíveis apenas dentro da função.
Here is a function `myTest` with a local variable called `loc`.
Aqui está uma função `myTest` com uma variável local chamada `loc`.
```js
function myTest() {
@ -22,17 +22,17 @@ myTest();
console.log(loc);
```
The `myTest()` function call will display the string `foo` in the console. The `console.log(loc)` line will throw an error, as `loc` is not defined outside of the function.
A chamada da função `myTest()` irá exibir a string `foo` no console. A linha `console.log(loc)` irá lançar um erro, já que `loc` não foi definido fora da função.
# --instructions--
The editor has two `console.log`s to help you see what is happening. Check the console as you code to see how it changes. Declare a local variable `myVar` inside `myLocalScope` and run the tests.
O editor possui dois `console.log` para te ajudar a ver o que está acontecendo. Verifique o console enquanto codifica para ver como muda. Declare uma variável local `myVar` dentro de `myLocalScope` e rode os testes.
**Note:** The console will still display `ReferenceError: myVar is not defined`, but this will not cause the tests to fail.
**Nota:** O console ainda exibirá `ReferenceError: myVar is not defined`, mas isso não causará falha nos testes.
# --hints--
The code should not contain a global `myVar` variable.
O código não deve conter uma variável global `myVar`.
```js
function declared() {
@ -41,7 +41,7 @@ function declared() {
assert.throws(declared, ReferenceError);
```
You should add a local `myVar` variable.
Você deve adicionar a variável local `myVar`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5690307fddb111c6084545d7
title: Logical Order in If Else Statements
title: Ordem Lógica em Instruções If Else
challengeType: 1
videoUrl: 'https://scrimba.com/c/cwNvMUV'
forumTopicId: 18228
@ -9,13 +9,13 @@ dashedName: logical-order-in-if-else-statements
# --description--
Order is important in `if`, `else if` statements.
Ordem é importante em instruções `if` e `else if`.
The function is executed from top to bottom so you will want to be careful of what statement comes first.
A função é executada de cima para baixo, então você deve ser cuidados com qual instrução vem primeiro.
Take these two functions as an example.
Tomem essas duas funções como exemplo.
Here's the first:
Aqui está a primeira:
```js
function foo(x) {
@ -29,7 +29,7 @@ function foo(x) {
}
```
And the second just switches the order of the statements:
E a segunda apenas altera a ordem das instruções if e else if:
```js
function bar(x) {
@ -43,34 +43,34 @@ function bar(x) {
}
```
While these two functions look nearly identical if we pass a number to both we get different outputs.
Embora as duas funções se pareçam praticamente idênticas, se nós passarmos um número para ambos nós teremos saídas diferentes.
```js
foo(0)
bar(0)
```
`foo(0)` will return the string `Less than one`, and `bar(0)` will return the string `Less than two`.
`foo(0)` retornará a string `Less than one`, e `bar(0)` retornará a string `Less than two`.
# --instructions--
Change the order of logic in the function so that it will return the correct statements in all cases.
Altere a ordem lógica na função para que retorne as instruções corretas em todos os cenários.
# --hints--
`orderMyLogic(4)` should return the string `Less than 5`
`orderMyLogic(4)` deve retornar a string `Less than 5`
```js
assert(orderMyLogic(4) === 'Less than 5');
```
`orderMyLogic(6)` should return the string `Less than 10`
`orderMyLogic(6)` deve retornar a string `Less than 10`
```js
assert(orderMyLogic(6) === 'Less than 10');
```
`orderMyLogic(11)` should return the string `Greater than or equal to 10`
`orderMyLogic(11)` deve retornar a string `Greater than or equal to 10`
```js
assert(orderMyLogic(11) === 'Greater than or equal to 10');

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392cc
title: Manipulate Arrays With pop()
title: Manipule Arrays com pop()
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRbVZAB'
forumTopicId: 18236
@ -9,11 +9,11 @@ dashedName: manipulate-arrays-with-pop
# --description--
Another way to change the data in an array is with the `.pop()` function.
Outra forma de alterar os dados em um array é com a função `.pop()`.
`.pop()` is used to pop a value off of the end of an array. We can store this popped off value by assigning it to a variable. In other words, `.pop()` removes the last element from an array and returns that element.
`.pop()` é usado para remover um valor do final do array. Nós podemos armazenar esse valor removido ao atribuir a saída da chamada do método a uma variável. Em outras palavras, `.pop()` remove o último elemento de um array e retorna aquele elemento.
Any type of entry can be popped off of an array - numbers, strings, even nested arrays.
Qualquer tipo de entrada pode ser removida de um array - numbers, strings e até mesmo arrays aninhados.
```js
var threeArr = [1, 4, 6];
@ -22,15 +22,15 @@ console.log(oneDown);
console.log(threeArr);
```
The first `console.log` will display the value `6`, and the second will display the value `[1, 4]`.
O primeiro `consol.log` exibirá o valor `6`, e o segundo irá exibir o valor `[1, 4]`.
# --instructions--
Use the `.pop()` function to remove the last item from `myArray`, assigning the popped off value to `removedFromMyArray`.
Use a função `.pop()` para remover o último item de `myArray`, atribuindo o valor removido para `removedFromMyArray`.
# --hints--
`myArray` should only contain `[["John", 23]]`.
`myArray` deve conter apenas `[["John", 23]]`.
```js
assert(
@ -44,13 +44,13 @@ assert(
);
```
You should use `pop()` on `myArray`.
Você deve usar `pop()` em `myArray`.
```js
assert(/removedFromMyArray\s*=\s*myArray\s*.\s*pop\s*(\s*)/.test(code));
```
`removedFromMyArray` should only contain `["cat", 2]`.
`removedFromMyArray` deve conter apenas `["cat", 2]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392cb
title: Manipulate Arrays With push()
title: Manipule Arrays Com push()
challengeType: 1
videoUrl: 'https://scrimba.com/c/cnqmVtJ'
forumTopicId: 18237
@ -9,11 +9,11 @@ dashedName: manipulate-arrays-with-push
# --description--
An easy way to append data to the end of an array is via the `push()` function.
Uma forma fácil de adicionar dados no final de um array é através da função `push()`.
`.push()` takes one or more <dfn>parameters</dfn> and "pushes" them onto the end of the array.
`.push()` recebe um ou mais <dfn>parâmetros</dfn> e "empurra" eles no final do array.
Examples:
Exemplos:
```js
var arr1 = [1,2,3];
@ -23,15 +23,15 @@ var arr2 = ["Stimpson", "J", "cat"];
arr2.push(["happy", "joy"]);
```
`arr1` now has the value `[1, 2, 3, 4]` and `arr2` has the value `["Stimpson", "J", "cat", ["happy", "joy"]]`.
`arr1` agora tem o valor de `[1, 2, 3, 4]` e `arr2` tem o valor de `["Stimpson", "J", "cat", ["happy", "joy"]]`.
# --instructions--
Push `["dog", 3]` onto the end of the `myArray` variable.
Empurre `["dog", 3]` no final da variável `myArray`.
# --hints--
`myArray` should now equal `[["John", 23], ["cat", 2], ["dog", 3]]`.
`myArray` agora deve ser igual a `[["John", 23], ["cat", 2], ["dog", 3]]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392cd
title: Manipulate Arrays With shift()
title: Manipule Arrays Com shift()
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRbVETW'
forumTopicId: 18238
@ -9,26 +9,26 @@ dashedName: manipulate-arrays-with-shift
# --description--
`pop()` always removes the last element of an array. What if you want to remove the first?
`pop()` sempre remove o último elemento de um array. E se você quiser remover o primeiro?
That's where `.shift()` comes in. It works just like `.pop()`, except it removes the first element instead of the last.
É aí que o `.shift()` vem a ser útil. Ele funciona da mesma forma que `.pop()`, exceto que ele remove o primeiro elemento ao invés do último.
Example:
Exemplo:
```js
var ourArray = ["Stimpson", "J", ["cat"]];
var removedFromOurArray = ourArray.shift();
```
`removedFromOurArray` would have a value of the string `Stimpson`, and `ourArray` would have `["J", ["cat"]]`.
`removedFromOurArray` teria o valor da string `Stimpson` e `ourArray` teria o valor de `["J", ["cat"]]`.
# --instructions--
Use the `.shift()` function to remove the first item from `myArray`, assigning the "shifted off" value to `removedFromMyArray`.
Use a função `.shift()` para remover o primeiro item de `myArray`, atribuindo o valor "removido" para `removedFromMyArray`.
# --hints--
`myArray` should now equal `[["dog", 3]]`.
`myArray` agora deve ser igual a `[["dog", 3]]`.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
`removedFromMyArray` should contain `["John", 23]`.
`removedFromMyArray` deve conter `["John", 23]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392ce
title: Manipulate Arrays With unshift()
title: Manipule Arrays Com unshift()
challengeType: 1
videoUrl: 'https://scrimba.com/c/ckNDESv'
forumTopicId: 18239
@ -9,11 +9,11 @@ dashedName: manipulate-arrays-with-unshift
# --description--
Not only can you `shift` elements off of the beginning of an array, you can also `unshift` elements to the beginning of an array i.e. add elements in front of the array.
Não só você pode `remover` elementos do início de um array, como você também pode `adicionar (unshift)` elementos ao início de um array i.e. adiciona elementos na frente do array.
`.unshift()` works exactly like `.push()`, but instead of adding the element at the end of the array, `unshift()` adds the element at the beginning of the array.
`.unshift()` funciona exatamente como `.push()`, mas ao invés de adicionar o elemento ao final do array, `unshift` adiciona o elemento no início do array.
Example:
Exemplo:
```js
var ourArray = ["Stimpson", "J", "cat"];
@ -21,15 +21,15 @@ ourArray.shift();
ourArray.unshift("Happy");
```
After the `shift`, `ourArray` would have the value `["J", "cat"]`. After the `unshift`, `ourArray` would have the value `["Happy", "J", "cat"]`.
Após o `shift`, `ourArray` teria o valor `["J","cat"]`. Após o `unshift`, `ourArray` teria o valor `["Happy","J","cat"]`.
# --instructions--
Add `["Paul",35]` to the beginning of the `myArray` variable using `unshift()`.
Adicione `["Paul",35]` ao início da variável `myArray` usando `unshift()`.
# --hints--
`myArray` should now have `[["Paul", 35], ["dog", 3]]`.
`myArray` agora deve ter `[["Paul", 35], ["dog", 3]]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244cb
title: Manipulating Complex Objects
title: Manipulando Objetos Complexos
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yNMfR'
forumTopicId: 18208
@ -9,9 +9,9 @@ dashedName: manipulating-complex-objects
# --description--
Sometimes you may want to store data in a flexible <dfn>Data Structure</dfn>. A JavaScript object is one way to handle flexible data. They allow for arbitrary combinations of <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, <dfn>functions</dfn>, and <dfn>objects</dfn>.
Às vezes você pode querer armazenar dados em uma <dfn>Estrutura de Dados</dfn> flexível. Um objeto JavaScript é uma forma de lidar com dados flexíveis. Eles permitem combinações arbitrárias de <dfn>strings</dfn>, <dfn>numbers</dfn>, <dfn>booleans</dfn>, <dfn>arrays</dfn>, <dfn>functions</dfn> e <dfn>objects</dfn>.
Here's an example of a complex data structure:
Aqui está um exemplo de estrutura de dados complexas:
```js
var ourMusic = [
@ -29,7 +29,7 @@ var ourMusic = [
];
```
This is an array which contains one object inside. The object has various pieces of <dfn>metadata</dfn> about an album. It also has a nested `formats` array. If you want to add more album records, you can do this by adding records to the top level array. Objects hold data in a property, which has a key-value format. In the example above, `"artist": "Daft Punk"` is a property that has a key of `artist` and a value of `Daft Punk`. [JavaScript Object Notation](http://www.json.org/) or `JSON` is a related data interchange format used to store data.
Isto é um array o qual contém um objeto dentro dele. O objeto possui vários pedaços de <dfn>metadados</dfn> sobre um album. Também possui um array aninhado `formats`. Se você quiser adicionar mais discos de album, você pode fazer isso ao adicionar os discos no array de alto nível. Objetos armazenam dados em uma propriedade, a qual possui um formato de chave-valor. No exemplo acima, `"artist": "Daft Punk"` é uma propriedade que tem uma chave `artist` e um valor de `Daft Punk`. [Notação de Objeto JavaScript](http://www.json.org/) ou `JSON` é um formato, de interalteração de dados relacionados, usado para armazenar dados.
```json
{
@ -45,39 +45,39 @@ This is an array which contains one object inside. The object has various pieces
}
```
**Note:** You will need to place a comma after every object in the array, unless it is the last object in the array.
**Nota:** Você precisará colocar uma vírgula após cada objeto no array, a não ser que for o último objeto no array.
# --instructions--
Add a new album to the `myMusic` array. Add `artist` and `title` strings, `release_year` number, and a `formats` array of strings.
Adicione um novo álbum para o array `myMusic`. Adicione strings: `artist` e `title`, número: `release_year`, e um array de strings: `formats`.
# --hints--
`myMusic` should be an array
`myMusic` deve ser um array
```js
assert(Array.isArray(myMusic));
```
`myMusic` should have at least two elements
`myMusic` deve ter pelo menos dois elementos
```js
assert(myMusic.length > 1);
```
The elements in the `myMusic` array should be objects
Os elementos no array `myMusic` devem ser objetos
```js
myMusic.forEach(object => {assert.typeOf(object, 'object')})
```
Your object in `myMusic` should have at least 4 properties
Seu objeto em `myMusic` deve ter pelo menos 4 propriedades
```js
myMusic.forEach(object => {assert(Object.keys(object).length > 3); });
```
Your object in `myMusic` should contain the property `artist` which is a string
Seu objeto em `myMusic` deve conter a propriedade `artist` a qual é uma string
```js
myMusic.forEach(object => {
@ -86,7 +86,7 @@ myMusic.forEach(object => {
})
```
Your object in `myMusic` should contain the property `title` which is a string
Seu objeto em `myMusic` deve conter a propriedade `title` a qual é uma string
```js
myMusic.forEach(object => {
@ -95,7 +95,7 @@ myMusic.forEach(object => {
})
```
Your object in `myMusic` should contain the property `release_year` which is a number
Seu objeto em `myMusic` deve conter a propriedade `release_year` a qual é um número
```js
myMusic.forEach(object => {
@ -104,7 +104,7 @@ myMusic.forEach(object => {
})
```
Your object in `myMusic` should contain a `formats` property which is an array
Seu objeto em `myMusic` deve conter a propriedade `formats` a qual é um array
```js
myMusic.forEach(object => {
@ -113,7 +113,7 @@ myMusic.forEach(object => {
})
```
`formats` should be an array of strings with at least two elements
`formats` deve ser um array de strings com pelo menos dois elementos
```js
myMusic.forEach(object => {

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb8bdef
title: Modify Array Data With Indexes
title: Modifique Dados de Array Com Índices
challengeType: 1
videoUrl: 'https://scrimba.com/c/czQM4A8'
forumTopicId: 18241
@ -9,26 +9,26 @@ dashedName: modify-array-data-with-indexes
# --description--
Unlike strings, the entries of arrays are <dfn>mutable</dfn> and can be changed freely.
Diferente de strings, as entradas de um array são <dfn>mutáveis</dfn> e pode ser modificadas livremente.
**Example**
**Exemplo**
```js
var ourArray = [50,40,30];
ourArray[0] = 15;
```
`ourArray` now has the value `[15, 40, 30]`.
`ourArray` agora tem o valor `[15, 40, 30]`.
**Note:** There shouldn't be any spaces between the array name and the square brackets, like `array [0]`. Although JavaScript is able to process this correctly, this may confuse other programmers reading your code.
**Nota:** Não deve ter espaços entre o nome do array e os colchetes, como `array [0]`. Embora JavaScript é capaz de processar isso corretamente, isso pode causar confusão em outros programadores lendo o seu código.
# --instructions--
Modify the data stored at index `0` of `myArray` to a value of `45`.
Modifique o dado armazenado no índice `0` de `myArray` para um valor de `45`.
# --hints--
`myArray` should now be `[45,64,99]`.
`myArray` agora deve ser `[45,64,99]`.
```js
assert(
@ -47,7 +47,7 @@ assert(
);
```
You should be using correct index to modify the value in `myArray`.
Você deve usar o índice correto para modificar o valor em `myArray`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244df
title: Multiple Identical Options in Switch Statements
title: Várias Opções Idênticas em Instruções Switch
challengeType: 1
videoUrl: 'https://scrimba.com/c/cdBKWCV'
forumTopicId: 18242
@ -9,7 +9,7 @@ dashedName: multiple-identical-options-in-switch-statements
# --description--
If the `break` statement is omitted from a `switch` statement's `case`, the following `case` statement(s) are executed until a `break` is encountered. If you have multiple inputs with the same output, you can represent them in a `switch` statement like this:
Se a instrução `break` for omitida de uma instrução `case` de um `switch`, as instruções seguintes `case` são executadas até que seja encontrado um `break`. Se você tem várias entradas com a mesma saída, você pode representá-los em uma instrução `switch` da seguinte forma:
```js
var result = "";
@ -24,80 +24,80 @@ switch(val) {
}
```
Cases for 1, 2, and 3 will all produce the same result.
Todos os casos para 1, 2 e 3 irão produzir o mesmo resultado.
# --instructions--
Write a switch statement to set `answer` for the following ranges:
Escreva uma instrução para definir `answer` para os seguintes intervalos:
`1-3` - `Low`
`4-6` - `Mid`
`7-9` - `High`
**Note:** You will need to have a `case` statement for each number in the range.
**Nota:** Você precisará ter uma instrução `case` para cada número no intervalo.
# --hints--
`sequentialSizes(1)` should return the string `Low`
`sequentialSizes(1)` deve retornar a string `Low`
```js
assert(sequentialSizes(1) === 'Low');
```
`sequentialSizes(2)` should return the string `Low`
`sequentialSizes(2)` deve retornar a string `Low`
```js
assert(sequentialSizes(2) === 'Low');
```
`sequentialSizes(3)` should return the string `Low`
`sequentialSizes(3)` deve retornar a string `Low`
```js
assert(sequentialSizes(3) === 'Low');
```
`sequentialSizes(4)` should return the string `Mid`
`sequentialSizes(4)` deve retornar a string `Mid`
```js
assert(sequentialSizes(4) === 'Mid');
```
`sequentialSizes(5)` should return the string `Mid`
`sequentialSizes(5)` deve retornar a string `Mid`
```js
assert(sequentialSizes(5) === 'Mid');
```
`sequentialSizes(6)` should return the string `Mid`
`sequentialSizes(6)` deve retornar a string `Mid`
```js
assert(sequentialSizes(6) === 'Mid');
```
`sequentialSizes(7)` should return the string `High`
`sequentialSizes(7)` deve retornar a string `High`
```js
assert(sequentialSizes(7) === 'High');
```
`sequentialSizes(8)` should return the string `High`
`sequentialSizes(8)` deve retornar a string `High`
```js
assert(sequentialSizes(8) === 'High');
```
`sequentialSizes(9)` should return the string `High`
`sequentialSizes(9)` deve retornar a string `High`
```js
assert(sequentialSizes(9) === 'High');
```
You should not use any `if` or `else` statements
Você não deve usar nenhuma das instruções `if` ou `else`
```js
assert(!/else/g.test(code) || !/if/g.test(code));
```
You should have nine `case` statements
Você deve ter nove instruções `case`
```js
assert(code.match(/case/g).length === 9);

View File

@ -1,6 +1,6 @@
---
id: bd7993c9c69feddfaeb7bdef
title: Multiply Two Decimals with JavaScript
title: Multiplique Dois Decimais com JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/ce2GeHq'
forumTopicId: 301173
@ -9,23 +9,23 @@ dashedName: multiply-two-decimals-with-javascript
# --description--
In JavaScript, you can also perform calculations with decimal numbers, just like whole numbers.
Em JavaScript, você também pode realizar cálculos com números decimais, assim como com números inteiros.
Let's multiply two decimals together to get their product.
Vamos multiplicar dois decimais juntos para obter o produto deles.
# --instructions--
Change the `0.0` so that product will equal `5.0`.
Altere o `0.0` para que o produto seja igual a `5.0`.
# --hints--
The variable `product` should equal `5.0`.
A variável `product` deve ser igual `5.0`.
```js
assert(product === 5.0);
```
You should use the `*` operator
Você deve usar o operador `*`
```js
assert(/\*/.test(code));

View File

@ -1,6 +1,6 @@
---
id: cf1231c1c11feddfaeb5bdef
title: Multiply Two Numbers with JavaScript
title: Multiplique Dois Números com JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cP3y3Aq'
forumTopicId: 18243
@ -9,31 +9,31 @@ dashedName: multiply-two-numbers-with-javascript
# --description--
We can also multiply one number by another.
Nós também podemos multiplicar um número por outro.
JavaScript uses the `*` symbol for multiplication of two numbers.
JavaScript usa o símbolo `*` para multiplicação de dois números.
**Example**
**Exemplo**
```js
myVar = 13 * 13;
```
`myVar` would have the value `169`.
`myVar` teria o valor `169`.
# --instructions--
Change the `0` so that product will equal `80`.
Altere o `0` para que o produto seja igual a `80`.
# --hints--
The variable `product` should be equal to 80.
A variável `product` deve ser igual a 80.
```js
assert(product === 80);
```
You should use the `*` operator.
Você deve usar o operador `*`.
```js
assert(/\*/.test(code));

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb7bdef
title: Nest one Array within Another Array
title: Aninhe um Array com Outro Array
challengeType: 1
videoUrl: 'https://scrimba.com/c/crZQZf8'
forumTopicId: 18247
@ -9,21 +9,21 @@ dashedName: nest-one-array-within-another-array
# --description--
You can also nest arrays within other arrays, like below:
Você também pode aninhar arrays dentro de outros arrays, como abaixo:
```js
[["Bulls", 23], ["White Sox", 45]]
```
This is also called a <dfn>multi-dimensional array</dfn>.
Isso é chamado um <dfn>array multidimensional</dfn>.
# --instructions--
Create a nested array called `myArray`.
Crie um array aninhado chamado de `myArray`.
# --hints--
`myArray` should have at least one array nested within another array.
`myArray` deve ter pelo menos um array aninhado dentro de outro array.
```js
assert(Array.isArray(myArray) && myArray.some(Array.isArray));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244e1
title: Nesting For Loops
title: Aninhando Laços For
challengeType: 1
videoUrl: 'https://scrimba.com/c/cRn6GHM'
forumTopicId: 18248
@ -9,7 +9,7 @@ dashedName: nesting-for-loops
# --description--
If you have a multi-dimensional array, you can use the same logic as the prior waypoint to loop through both the array and any sub-arrays. Here is an example:
Se você possui um array multidimensional, você pode usar a mesma lógica no ponto de passagem anterior para iterar através ambos os arrays e qualquer sub-arrays. Aqui está um exemplo:
```js
var arr = [
@ -22,21 +22,21 @@ for (var i=0; i < arr.length; i++) {
}
```
This outputs each sub-element in `arr` one at a time. Note that for the inner loop, we are checking the `.length` of `arr[i]`, since `arr[i]` is itself an array.
Isso exibi no console cada sub elemento dentro de `arr`, um de cada vez. Note que para o laço interno, nós estamos verificando a propriedade `.length` de `arr[i]`, desde que `arr[i]` também é um array.
# --instructions--
Modify function `multiplyAll` so that it returns the product of all the numbers in the sub-arrays of `arr`.
Modifique a função `multiplyAll` para que retorne o produto de todos os números nos sub arrays de `arr`.
# --hints--
`multiplyAll([[1],[2],[3]])` should return `6`
`multiplyAll([[1],[2],[3]])` deve retornar `6`
```js
assert(multiplyAll([[1], [2], [3]]) === 6);
```
`multiplyAll([[1,2],[3,4],[5,6,7]])` should return `5040`
`multiplyAll([[1,2],[3,4],[5,6,7]])` deve retornar `5040`
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` should return `54`
`multiplyAll([[5,1],[0.2, 4, 0.5],[3, 9]])` deve retornar `54`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244bd
title: Passing Values to Functions with Arguments
title: Passando Valores para Funções com Argumentos
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy8rahW'
forumTopicId: 18254
@ -9,9 +9,9 @@ dashedName: passing-values-to-functions-with-arguments
# --description--
<dfn>Parameters</dfn> are variables that act as placeholders for the values that are to be input to a function when it is called. When a function is defined, it is typically defined along with one or more parameters. The actual values that are input (or <dfn>"passed"</dfn>) into a function when it is called are known as <dfn>arguments</dfn>.
<dfn>Parâmetros</dfn> são variáveis que atuam como espaços reservados para os valores que são passados para uma função, quando ela é chamada. Quando uma função é definida, normalmente ela é definida junto com um ou mais parâmetros. Os valores reais que são entradas de (ou <dfn>"passadas"</dfn> para) uma função quando ela é chamada são conhecidos como <dfn>argumentos</dfn>.
Here is a function with two parameters, `param1` and `param2`:
Aqui está uma função com dois parâmetros, `param1` e `param2`:
```js
function testFun(param1, param2) {
@ -19,21 +19,21 @@ function testFun(param1, param2) {
}
```
Then we can call `testFun` like this: `testFun("Hello", "World");`. We have passed two string arguments, `Hello` and `World`. Inside the function, `param1` will equal the string `Hello` and `param2` will equal the string `World`. Note that you could call `testFun` again with different arguments and the parameters would take on the value of the new arguments.
Então podemos chamar o `testFun` dessa forma: `testFun("Hello", "World");`. Passamos dois argumentos do tipo string, `Hello` e `World`. Dentro da função, `param1` será igual à string `Hello` e `param2` será igual à string `World`. Note que você poderia chamar o `testFun` novamente com diferentes argumentos e os parâmetros assumiriam o valor dos novos argumentos.
# --instructions--
<ol><li>Create a function called <code>functionWithArgs</code> that accepts two arguments and outputs their sum to the dev console.</li><li>Call the function with two numbers as arguments.</li></ol>
<ol><li>Crie uma função chamada <code>functionWithArgs</code> que aceita dois argumentos e exibe seus valores no console de desenvolvimento.</li><li>Chame a função com dois números como argumentos.</li></ol>
# --hints--
`functionWithArgs` should be a function.
`functionWithArgs` deve ser uma função.
```js
assert(typeof functionWithArgs === 'function');
```
`functionWithArgs(1,2)` should output `3`.
`functionWithArgs(1,2)` deve exibir no console `3`.
```js
if (typeof functionWithArgs === 'function') {
@ -44,7 +44,7 @@ if (typeof functionWithArgs === 'function') {
assert(logOutput == 3);
```
`functionWithArgs(7,9)` should output `16`.
`functionWithArgs(7,9)` deve exibir no console `16`.
```js
if (typeof functionWithArgs === 'function') {
@ -55,7 +55,7 @@ if (typeof functionWithArgs === 'function') {
assert(logOutput == 16);
```
You should call `functionWithArgs` with two numbers after you define it.
Você deve chamar a função `functionWithArgs` com dois números depois de defini-la.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 599a789b454f2bbd91a3ff4d
title: Practice comparing different values
title: Pratique comparar diferentes valores
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm8PqCa'
forumTopicId: 301174
@ -9,42 +9,42 @@ dashedName: practice-comparing-different-values
# --description--
In the last two challenges, we learned about the equality operator (`==`) and the strict equality operator (`===`). Let's do a quick review and practice using these operators some more.
Nos últimos dois desafios, aprendemos sobre o operador de igualdade (`==`) e o operador de igualdade estrita (`===`). Vamos fazer uma breve revisão e praticar usando esses operadores mais uma vez.
If the values being compared are not of the same type, the equality operator will perform a type conversion, and then evaluate the values. However, the strict equality operator will compare both the data type and value as-is, without converting one type to the other.
Se os valores sendo comparados não são do mesmo tipo, o operador de igualdade irá fazer a conversão de tipo e, então, avaliar os valores. No entanto, o operador de igualdade estrita irá comparar ambos os tipos de dados e os valores, sem converter de um tipo para outro.
**Examples**
**Exemplos**
`3 == '3'` returns `true` because JavaScript performs type conversion from string to number. `3 === '3'` returns false because the types are different and type conversion is not performed.
`3 == '3'` retorna `true` porque JavaScript faz a conversão de tipo de string para número. `3 === '3'` retorna falso porque os tipos são diferentes e não é feita a conversão de tipo.
**Note:** In JavaScript, you can determine the type of a variable or a value with the `typeof` operator, as follows:
**Nota:** Em JavaScript, você pode determinar o tipo de uma variável ou de um valor, com o operador `typeof`, como se segue:
```js
typeof 3
typeof '3'
```
`typeof 3` returns the string `number`, and `typeof '3'` returns the string `string`.
`typeof 3` retorna a string `number` e `typeof '3'` retorna a string `string`.
# --instructions--
The `compareEquality` function in the editor compares two values using the equality operator. Modify the function so that it returns the string `Equal` only when the values are strictly equal.
A função `compareEquality` no editor compara dois valores usando o operador de igualdade. Modifique a função para que ela retorne a string `Equal` apenas quando os valores forem estritamente iguais.
# --hints--
`compareEquality(10, "10")` should return the string `Not Equal`
`compareEquality(10, "10")` deve retornar a string `Not Equal`
```js
assert(compareEquality(10, '10') === 'Not Equal');
```
`compareEquality("20", 20)` should return the string `Not Equal`
`compareEquality("20", 20)` deve retornar a string `Not Equal`
```js
assert(compareEquality('20', 20) === 'Not Equal');
```
You should use the `===` operator
Você deve usar o operador `===`
```js
assert(code.match(/===/g));

View File

@ -1,6 +1,6 @@
---
id: 5688e62ea601b2482ff8422b
title: Profile Lookup
title: Busca de Perfil
challengeType: 1
videoUrl: 'https://scrimba.com/c/cDqW2Cg'
forumTopicId: 18259
@ -9,27 +9,27 @@ dashedName: profile-lookup
# --description--
We have an array of objects representing different people in our contacts lists.
Nós temos um array de objetos representando pessoas diferentes nas nossas listas de contatos.
A `lookUpProfile` function that takes `name` and a property (`prop`) as arguments has been pre-written for you.
Uma função `lookUpProfile`, que recebe `name` e uma propriedade (`prop`) como argumentos, foi pré-escrita para você.
The function should check if `name` is an actual contact's `firstName` and the given property (`prop`) is a property of that contact.
A função deve verificar se `name` é o `firstName` (primeiro nome) de um contato e se a propriedade passada (`prop`) é uma propriedade daquele contato.
If both are true, then return the "value" of that property.
Se ambos forem verdadeiros, então retorne o "valor" daquela propriedade.
If `name` does not correspond to any contacts then return the string `No such contact`.
Se `name` não corresponder a nenhum dos contatos, então retorne a string `No such contact`.
If `prop` does not correspond to any valid properties of a contact found to match `name` then return the string `No such property`.
Se `prop` não corresponder a nenhuma propriedade válida de um contato encontrado para coincidir com `name` então retorne a string `No such property`.
# --hints--
`lookUpProfile("Kristian", "lastName")` should return the string `Vos`
`lookUpProfile("Kristian", "lastName")` deve retornar a string `Vos`
```js
assert(lookUpProfile('Kristian', 'lastName') === 'Vos');
```
`lookUpProfile("Sherlock", "likes")` should return `["Intriguing Cases", "Violin"]`
`lookUpProfile("Sherlock", "likes")` deve retornar `["Intriguing Cases", "Violin"]`
```js
assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
@ -38,25 +38,25 @@ assert.deepEqual(lookUpProfile('Sherlock', 'likes'), [
]);
```
`lookUpProfile("Harry", "likes")` should return an array
`lookUpProfile("Harry", "likes")` deve retornar um array
```js
assert(typeof lookUpProfile('Harry', 'likes') === 'object');
```
`lookUpProfile("Bob", "number")` should return the string `No such contact`
`lookUpProfile("Bob", "number")` deve retornar a string `No such contact`
```js
assert(lookUpProfile('Bob', 'number') === 'No such contact');
```
`lookUpProfile("Bob", "potato")` should return the string `No such contact`
`lookUpProfile("Bob", "potato")` deve retornar a string `No such contact`
```js
assert(lookUpProfile('Bob', 'potato') === 'No such contact');
```
`lookUpProfile("Akira", "address")` should return the string `No such property`
`lookUpProfile("Akira", "address")` deve retornar a string `No such property`
```js
assert(lookUpProfile('Akira', 'address') === 'No such property');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244b4
title: Quoting Strings with Single Quotes
title: Cercando uma String com Aspas Simples
challengeType: 1
videoUrl: 'https://scrimba.com/c/cbQmnhM'
forumTopicId: 18260
@ -9,41 +9,41 @@ dashedName: quoting-strings-with-single-quotes
# --description--
<dfn>String</dfn> values in JavaScript may be written with single or double quotes, as long as you start and end with the same type of quote. Unlike some other programming languages, single and double quotes work the same in JavaScript.
Valores de <dfn>String</dfn> em JavaScript podem ser escritas com aspas simples ou duplas, desde que você comece e termine com o mesmo tipo de aspas. Diferente de outras linguagens de programação, aspas simples e duplas funcionam da mesma forma em JavaScript.
```js
doubleQuoteStr = "This is a string";
singleQuoteStr = 'This is also a string';
```
The reason why you might want to use one type of quote over the other is if you want to use both in a string. This might happen if you want to save a conversation in a string and have the conversation in quotes. Another use for it would be saving an `<a>` tag with various attributes in quotes, all within a string.
O motivo pelo qual você pode querer usar um tipo de aspas no lugar da outra, é se você vir a querer usar ambas em uma string. Isso pode acontecer se você quiser salvar uma conversa em uma string e ter a conversa entre aspas. Outro uso para isso seria salvar uma tag `<a>` com vários atributos em aspas, tudo dentro de uma string.
```js
conversation = 'Finn exclaims to Jake, "Algebraic!"';
```
However, this becomes a problem if you need to use the outermost quotes within it. Remember, a string has the same kind of quote at the beginning and end. But if you have that same quote somewhere in the middle, the string will stop early and throw an error.
Porém, isso se torna um problema se você precisar usar as aspas mais extremas dentro dela. Lembre-se, uma string tem o mesmo tipo de aspas no início e no final. Mas se você tem aquela mesma aspa em algum lugar no meio, a string irá terminar mais cedo e lançará um erro.
```js
goodStr = 'Jake asks Finn, "Hey, let\'s go on an adventure?"';
badStr = 'Finn responds, "Let's go!"';
```
Here `badStr` will throw an error.
Aqui `badStr` lançará um erro.
In the <dfn>goodStr</dfn> above, you can use both quotes safely by using the backslash `\` as an escape character.
Na string <dfn>goodStr</dfn> acima, você pode usar ambas as aspas com segurança ao usar a barra invertida `\` como um caractere de escapamento.
**Note:** The backslash `\` should not be confused with the forward slash `/`. They do not do the same thing.
**Nota:** A barra invertida `\` não deve ser confundida com a barra comum `/`. Elas não fazem a mesma coisa.
# --instructions--
Change the provided string to a string with single quotes at the beginning and end and no escape characters.
Altere a string fornecida para uma string com aspas simples no início e no final e sem caracteres de escapamento.
Right now, the `<a>` tag in the string uses double quotes everywhere. You will need to change the outer quotes to single quotes so you can remove the escape characters.
Nesse momento, a tag `<a>` na string usa aspas duplas em todo canto. Você precisará alterar as aspas mais externas em aspas simples, para que você possa remover os caracteres de escapamento.
# --hints--
You should remove all the backslashes (`\`).
Você deve remover todas as barras invertidas (`\`).
```js
assert(
@ -54,7 +54,7 @@ assert(
);
```
You should have two single quotes `'` and four double quotes `"`.
Você deve ter duas aspas simples `'` e quatro aspas duplas `"`.
```js
assert(code.match(/"/g).length === 4 && code.match(/'/g).length === 2);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244cf
title: Record Collection
title: Coleção de Disco
challengeType: 1
forumTopicId: 18261
dashedName: record-collection
@ -8,21 +8,21 @@ dashedName: record-collection
# --description--
You are given an object literal representing a part of your musical album collection. Each album has a unique id number as its key and several other properties. Not all albums have complete information.
Você recebeu um objeto literal representando uma parte da sua coleção de álbuns musicais. Cada álbum possui um número de id único como sua chave e diversas outras propriedades. Nem todos os álbuns possuem informações completas.
You start with an `updateRecords` function that takes an object literal, `records`, containing the musical album collection, an `id`, a `prop` (like `artist` or `tracks`), and a `value`. Complete the function using the rules below to modify the object passed to the function.
Você começa com uma função `updateRecords` que recebe um objeto literal, `records`, contendo a coleção de álbuns musicais, um `id`, uma </code>prop</code>(like `artist` ou `tracks`) e um `vlaue`. Complete a função usando as regras abaixo para modificar o objeto passado para a função.
- Your function must always return the entire record collection object.
- If `prop` isn't `tracks` and `value` isn't an empty string, update or set that album's `prop` to `value`.
- If `prop` is `tracks` but the album doesn't have a `tracks` property, create an empty array and add `value` to it.
- If `prop` is `tracks` and `value` isn't an empty string, add `value` to the end of the album's existing `tracks` array.
- If `value` is an empty string, delete the given `prop` property from the album.
- Sua função precisa sempre retornar o objeto de coleção de discos completo.
- Se `prop` não for `tracks` e `value` não for uma string vazia, atualize ou defina aquela `prop` do album como `value`.
- Se `prop` for `tracks` mas o álbum não tiver uma propriedade `tracks`, crie um array vazio e adicione o `value` nesse array.
- Se `prop` for `tracks` e `value` não for uma string vazia, adicione `value` ao final do array existente de `tracks` do álbum.
- Se `value` for uma string vazia, remova a propriedade `prop` recebida do álbum.
**Note:** A copy of the `recordCollection` object is used for the tests.
**Nota:** Uma cópia do objeto `recordCollection` é usada para testes.
# --hints--
After `updateRecords(recordCollection, 5439, "artist", "ABBA")`, `artist` should be the string `ABBA`
Após `updateRecords(recordCollection, 5439, "artist", "ABBA")`, `artist` deve ser aa string `ABBA`
```js
assert(
@ -31,7 +31,7 @@ assert(
);
```
After `updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me")`, `tracks` should have the string `Take a Chance on Me` as the last element.
Após `updateRecords(recordCollection, 5439, "tracks", "Take a Chance on Me")`, `tracks` deve ter a string `Take a Chance on Me` como último elemento.
```js
assert(
@ -41,14 +41,14 @@ assert(
);
```
After `updateRecords(recordCollection, 2548, "artist", "")`, `artist` should not be set
Após `updateRecords(recordCollection, 2548, "artist", "")`, `artist` não deve ser definido
```js
updateRecords(_recordCollection, 2548, 'artist', '');
assert(!_recordCollection[2548].hasOwnProperty('artist'));
```
After `updateRecords(recordCollection, 1245, "tracks", "Addicted to Love")`, `tracks` should have the string `Addicted to Love` as the last element.
Após `updateRecords(recordCollection, 1245, "tracks", "Addicted to Love")`, `tracks` deve ter a string `Addicted to Love` como o último elemento.
```js
assert(
@ -58,7 +58,7 @@ assert(
);
```
After `updateRecords(recordCollection, 2468, "tracks", "Free")`, `tracks` should have the string `1999` as the first element.
Após `updateRecords(recordCollection, 2468, "tracks", "Free")`, `tracks` deve ter a string `1999` como o último elemento. Após.
```js
assert(
@ -68,14 +68,14 @@ assert(
);
```
After `updateRecords(recordCollection, 2548, "tracks", "")`, `tracks` should not be set
Após `updateRecords(recordCollection, 2548, "tracks", "")`, `tracks` não deve ser definido
```js
updateRecords(_recordCollection, 2548, 'tracks', '');
assert(!_recordCollection[2548].hasOwnProperty('tracks'));
```
After `updateRecords(recordCollection, 1245, "albumTitle", "Riptide")`, `albumTitle` should be the string `Riptide`
Após `updateRecords(recordCollection, 1245, "albumTitle", "Riptide")`, `albumTitle` deve ser a string `Riptide`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5cfa3679138e7d9595b9d9d4
title: Replace Loops using Recursion
title: Substituir Laços com Recursividade
challengeType: 1
videoUrl: >-
https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/
@ -10,7 +10,7 @@ dashedName: replace-loops-using-recursion
# --description--
Recursion is the concept that a function can be expressed in terms of itself. To help understand this, start by thinking about the following task: multiply the first `n` elements of an array to create the product of those elements. Using a `for` loop, you could do this:
Recursividade é o conceito de que uma função pode ser chamada por ela mesmo. Para ajudar a entender isso, comece a pensar sobre a seguinte tarefa: multiplique os primeiros `n` elementos de um array para criar o produto desses elementos. Usando um laço `for`, você poderia fazer isso:
```js
function multiply(arr, n) {
@ -22,7 +22,7 @@ Recursion is the concept that a function can be expressed in terms of itself. To
}
```
However, notice that `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. That means you can rewrite `multiply` in terms of itself and never need to use a loop.
No entanto, note que `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. Isso significa que você pode rescreve `multiply` dentro da própria função e nunca precisar de usar um laço.
```js
function multiply(arr, n) {
@ -34,35 +34,35 @@ However, notice that `multiply(arr, n) == multiply(arr, n - 1) * arr[n - 1]`. Th
}
```
The recursive version of `multiply` breaks down like this. In the <dfn>base case</dfn>, where `n <= 0`, it returns 1. For larger values of `n`, it calls itself, but with `n - 1`. That function call is evaluated in the same way, calling `multiply` again until `n <= 0`. At this point, all the functions can return and the original `multiply` returns the answer.
A versão recursiva de `multiply` fica dessa forma. No <dfn>caso de base</dfn>, onde `n <= 0`, ele retorna 1. Para valores maiores de `n`, a função chama a si mesmo, mas com `n - 1`. Essa chamada da função é avaliada da mesma forma, chamando `multiply` novamente até que `n <= 0`. Nesse ponto, todas as funções podem retornar e a função `multiply` original retorna a resposta.
**Note:** Recursive functions must have a base case when they return without calling the function again (in this example, when `n <= 0`), otherwise they can never finish executing.
**Nota:** Funções recursivas precisam ter um caso base quando elas retornam sem chamar a função novamente (nesse exemplo, quando `n <= 0`), caso contrário, elas nunca irão parar de executar.
# --instructions--
Write a recursive function, `sum(arr, n)`, that returns the sum of the first `n` elements of an array `arr`.
Escreva uma função recursiva, `sum(arr, n)`, que retorna a soma dos primeiros `n` elementos de um array `arr`.
# --hints--
`sum([1], 0)` should equal 0.
`sum([1], 0)` deve ser igual a 0.
```js
assert.equal(sum([1], 0), 0);
```
`sum([2, 3, 4], 1)` should equal 2.
`sum([2, 3, 4], 1)` deve ser igual a 2.
```js
assert.equal(sum([2, 3, 4], 1), 2);
```
`sum([2, 3, 4, 5], 3)` should equal 9.
`sum([2, 3, 4, 5], 3)` deve ser igual a 9.
```js
assert.equal(sum([2, 3, 4, 5], 3), 9);
```
Your code should not rely on any kind of loops (`for` or `while` or higher order functions such as `forEach`, `map`, `filter`, or `reduce`.).
Seu código não deve depender de nenhum laço (`for` ou `while` ou funções de ordem superior como as funções `forEach`, `map`, `filter` ou `reduce`.).
```js
assert(
@ -70,7 +70,7 @@ assert(
);
```
You should use recursion to solve this problem.
Você deve usar recursividade para resolver o problema.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244e0
title: Replacing If Else Chains with Switch
title: Substituir Cadeias de If Else por Switch
challengeType: 1
videoUrl: 'https://scrimba.com/c/c3JE8fy'
forumTopicId: 18266
@ -9,7 +9,7 @@ dashedName: replacing-if-else-chains-with-switch
# --description--
If you have many options to choose from, a `switch` statement can be easier to write than many chained `if`/`else if` statements. The following:
Se você tiver muitas opções para escolher, uma instrução `switch` pode ser mais fácil de escrever do que muitas instruções `if`/`else if` encadeadas. O seguinte:
```js
if (val === 1) {
@ -21,7 +21,7 @@ if (val === 1) {
}
```
can be replaced with:
pode ser substituído por:
```js
switch(val) {
@ -38,65 +38,65 @@ switch(val) {
# --instructions--
Change the chained `if`/`else if` statements into a `switch` statement.
Altere a cadeia de instruções `if`/`else if` em um comando `switch`.
# --hints--
You should not use any `else` statements anywhere in the editor
Você não deve usar nenhuma instrução `else` em nenhum lugar no editor
```js
assert(!/else/g.test(code));
```
You should not use any `if` statements anywhere in the editor
Você não deve usar nenhuma instrução `if` em nenhum lugar no editor
```js
assert(!/if/g.test(code));
```
You should have at least four `break` statements
Você deve ter pelo menos instruções `break`
```js
assert(code.match(/break/g).length >= 4);
```
`chainToSwitch("bob")` should be the string `Marley`
`chainToSwitch("bob")` deve ser a string `Marley`
```js
assert(chainToSwitch('bob') === 'Marley');
```
`chainToSwitch(42)` should be the string `The Answer`
`chainToSwitch(42)` deve ser a string `The Answer`
```js
assert(chainToSwitch(42) === 'The Answer');
```
`chainToSwitch(1)` should be the string `There is no #1`
`chainToSwitch(1)` deve ser a string `There is no #1`
```js
assert(chainToSwitch(1) === 'There is no #1');
```
`chainToSwitch(99)` should be the string `Missed me by this much!`
`chainToSwitch(99)` deve ser a string `Missed me by this much!`
```js
assert(chainToSwitch(99) === 'Missed me by this much!');
```
`chainToSwitch(7)` should be the string `Ate Nine`
`chainToSwitch(7)` deve ser a string `Ate Nine`
```js
assert(chainToSwitch(7) === 'Ate Nine');
```
`chainToSwitch("John")` should be `""` (empty string)
`chainToSwitch("John")` deve ser `""` (string vazia)
```js
assert(chainToSwitch('John') === '');
```
`chainToSwitch(156)` should be `""` (empty string)
`chainToSwitch(156)` deve ser `""` (string vazia)
```js
assert(chainToSwitch(156) === '');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c2
title: Return a Value from a Function with Return
title: Retorne um Valor de uma Função com Return
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy87wue'
forumTopicId: 18271
@ -9,9 +9,9 @@ dashedName: return-a-value-from-a-function-with-return
# --description--
We can pass values into a function with <dfn>arguments</dfn>. You can use a `return` statement to send a value back out of a function.
Nós podemos passar valores para uma função com <dfn>argumentos</dfn>. Você pode usar uma instrução `return` para enviar um valor para fora de uma função.
**Example**
**Exemplo**
```js
function plusThree(num) {
@ -20,35 +20,35 @@ function plusThree(num) {
var answer = plusThree(5);
```
`answer` has the value `8`.
`answer` tem o valor de `8`.
`plusThree` takes an <dfn>argument</dfn> for `num` and returns a value equal to `num + 3`.
`plusThree` recebe um <dfn>argumento</dfn> para `num` e retorna um valor igual a `num + 3`.
# --instructions--
Create a function `timesFive` that accepts one argument, multiplies it by `5`, and returns the new value.
Crie uma função `timesFive` que aceita um argumento, multiplica ele por `5` e retorna o novo valor.
# --hints--
`timesFive` should be a function
`timesFive` deve ser uma função
```js
assert(typeof timesFive === 'function');
```
`timesFive(5)` should return `25`
`timesFive(5)` deve retornar `25`
```js
assert(timesFive(5) === 25);
```
`timesFive(2)` should return `10`
`timesFive(2)` deve retornar `10`
```js
assert(timesFive(2) === 10);
```
`timesFive(0)` should return `0`
`timesFive(0)` deve retornar `0`
```js
assert(timesFive(0) === 0);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c4
title: Return Early Pattern for Functions
title: Retornar o Padrão Inicial para Funções
challengeType: 1
videoUrl: 'https://scrimba.com/c/cQe39Sq'
forumTopicId: 18272
@ -9,9 +9,9 @@ dashedName: return-early-pattern-for-functions
# --description--
When a `return` statement is reached, the execution of the current function stops and control returns to the calling location.
Quando uma instrução `return` é alcançada, a execução da função atual para e retorna o código para o local da chamada da função.
**Example**
**Exemplo**
```js
function myFun() {
@ -22,54 +22,54 @@ function myFun() {
myFun();
```
The above will display the string `Hello` in the console, and return the string `World`. The string `byebye` will never display in the console, because the function exits at the `return` statement.
O código acima exibirá no console a string `Hello`, e retorna a string `World`. A string `byebye` nunca irá ser exibida no console, porque a função termina na instrução `return`.
# --instructions--
Modify the function `abTest` so that if `a` or `b` are less than `0` the function will immediately exit with a value of `undefined`.
Modifique a função `abTest` para que se `a` ou `b` forem menores que `0` a função irá imediatamente terminar retornando o valor de `undefined`.
**Hint**
Remember that [`undefined` is a keyword](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables), not a string.
**Dica**
Lembre-se que [`undefined` é uma palavra-chave](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/understanding-uninitialized-variables) e não uma string.
# --hints--
`abTest(2,2)` should return a number
`abTest(2,2)` deve retornar um número
```js
assert(typeof abTest(2, 2) === 'number');
```
`abTest(2,2)` should return `8`
`abTest(2,2)` deve retornar `8`
```js
assert(abTest(2, 2) === 8);
```
`abTest(-2,2)` should return `undefined`
`abTest(-2,2)` deve retornar `undefined`
```js
assert(abTest(-2, 2) === undefined);
```
`abTest(2,-2)` should return `undefined`
`abTest(2,-2)` deve retornar `undefined`
```js
assert(abTest(2, -2) === undefined);
```
`abTest(2,8)` should return `18`
`abTest(2,8)` deve retornar `18`
```js
assert(abTest(2, 8) === 18);
```
`abTest(3,3)` should return `12`
`abTest(3,3)` deve retornar `12`
```js
assert(abTest(3, 3) === 12);
```
`abTest(0,0)` should return `0`
`abTest(0,0)` deve retornar `0`
```js
assert(abTest(0, 0) === 0);

View File

@ -1,6 +1,6 @@
---
id: 5679ceb97cbaa8c51670a16b
title: Returning Boolean Values from Functions
title: Retornando Valores Booleanos das Funções
challengeType: 1
videoUrl: 'https://scrimba.com/c/cp62qAQ'
forumTopicId: 18273
@ -9,9 +9,9 @@ dashedName: returning-boolean-values-from-functions
# --description--
You may recall from [Comparison with the Equality Operator](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) that all comparison operators return a boolean `true` or `false` value.
Você pode se lembrar de [Comparação com o Operador de Igualdade](/learn/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator) que todas os operadores de comparação retornam um valor booleano `true` ou `false`.
Sometimes people use an `if/else` statement to do a comparison, like this:
As vezes as pessoas usam uma instrução `if/else` para fazer uma comparação, dessa forma:
```js
function isEqual(a,b) {
@ -23,7 +23,7 @@ function isEqual(a,b) {
}
```
But there's a better way to do this. Since `===` returns `true` or `false`, we can return the result of the comparison:
Mas há uma forma melhor de fazer isso. Já que `===` retorna `true` ou `false`, podemos retornar o resultado da comparação:
```js
function isEqual(a,b) {
@ -33,23 +33,23 @@ function isEqual(a,b) {
# --instructions--
Fix the function `isLess` to remove the `if/else` statements.
Corrija a função `isLess` para remover as instruções `if/else`.
# --hints--
`isLess(10,15)` should return `true`
`isLess(10,15)` deve retornar `true`
```js
assert(isLess(10, 15) === true);
```
`isLess(15,10)` should return `false`
`isLess(15,10)` deve retornar `false`
```js
assert(isLess(15, 10) === false);
```
You should not use any `if` or `else` statements
Você não deve usar nenhuma das instruções `if` ou `else`
```js
assert(!/if|else/g.test(code));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244dd
title: Selecting from Many Options with Switch Statements
title: Selecionando de Muitas Opções com Instruções Switch
challengeType: 1
videoUrl: 'https://scrimba.com/c/c4mv4fm'
forumTopicId: 18277
@ -9,9 +9,9 @@ dashedName: selecting-from-many-options-with-switch-statements
# --description--
If you have many options to choose from, use a <dfn>switch</dfn> statement. A `switch` statement tests a value and can have many <dfn>case</dfn> statements which define various possible values. Statements are executed from the first matched `case` value until a `break` is encountered.
Se você possui muitas opções pra escolher, use uma instrução <dfn>switch</dfn>. Uma instrução `switch` testa um valor e pode ter muitas instruções <dfn>case</dfn> as quais definem os diversos valores possíveis. Instruções são executadas desde o primeiro `case` correspondente até que encontre um `break`.
Here is an example of a `switch` statement:
Aqui está um exemplo de uma instrução `switch`:
```js
switch(lowercaseLetter) {
@ -24,11 +24,11 @@ switch(lowercaseLetter) {
}
```
`case` values are tested with strict equality (`===`). The `break` tells JavaScript to stop executing statements. If the `break` is omitted, the next statement will be executed.
Valores `case` são testados com o operador de igualdade estrita (`===`). O `break` diz ao JavaScript parar a execução das instruções. Se o `break` for omitido, a próxima instrução case será executada.
# --instructions--
Write a switch statement which tests `val` and sets `answer` for the following conditions:
Escreva uma instrução switch que testa `val` e define `answer` para as seguintes condições:
`1` - `alpha`
`2` - `beta`
`3` - `gamma`
@ -36,37 +36,37 @@ Write a switch statement which tests `val` and sets `answer` for the following c
# --hints--
`caseInSwitch(1)` should have a value of the string `alpha`
`caseInSwitch(1)` deve ter o valor da string `alpha`
```js
assert(caseInSwitch(1) === 'alpha');
```
`caseInSwitch(2)` should have a value of the string `beta`
`caseInSwitch(2)` deve ter o valor da string `beta`
```js
assert(caseInSwitch(2) === 'beta');
```
`caseInSwitch(3)` should have a value of the string `gamma`
`caseInSwitch(3)` deve ter o valor da string `gamma`
```js
assert(caseInSwitch(3) === 'gamma');
```
`caseInSwitch(4)` should have a value of the string `delta`
`caseInSwitch(4)` deve ter o valor da string `delta`
```js
assert(caseInSwitch(4) === 'delta');
```
You should not use any `if` or `else` statements
Você não deve usar nenhuma instrução `if` ou `else`
```js
assert(!/else/g.test(code) || !/if/g.test(code));
```
You should have at least 3 `break` statements
Você deve ter pelo menos 3 instruções `break`
```js
assert(code.match(/break/g).length > 2);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244bc
title: Shopping List
title: Lista de Compras
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9MEKHZ'
forumTopicId: 18280
@ -9,37 +9,37 @@ dashedName: shopping-list
# --description--
Create a shopping list in the variable `myList`. The list should be a multi-dimensional array containing several sub-arrays.
Crie uma lista de compras na variável `myList`. A lista deve ser um array multidimensional contendo diversos sub arrays.
The first element in each sub-array should contain a string with the name of the item. The second element should be a number representing the quantity i.e.
O primeiro elemento em cada sub array deve conter uma string com o nome do item. O segundo elemento deve ser um número representando a quantidade i.e.
```js
["Chocolate Bar", 15]
```
There should be at least 5 sub-arrays in the list.
Deve ter pelo menos 5 sub arrays na lista.
# --hints--
`myList` should be an array.
`myList` deve ser um array.
```js
assert(isArray);
```
The first elements in each of your sub-arrays should all be strings.
Os primeiros elementos em cada um dos seus sub arrays devem ser todos strings.
```js
assert(hasString);
```
The second elements in each of your sub-arrays should all be numbers.
Os segundos elementos em cada um de seus sub arrays devem ser todos números.
```js
assert(hasNumber);
```
You should have at least 5 items in your list.
Você deve ter pelo menos 5 items na sua lista.
```js
assert(count > 4);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244c6
title: Stand in Line
title: Fique na Linha
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8Q8tP'
forumTopicId: 18307
@ -9,41 +9,41 @@ dashedName: stand-in-line
# --description--
In Computer Science a <dfn>queue</dfn> is an abstract <dfn>Data Structure</dfn> where items are kept in order. New items can be added at the back of the queue and old items are taken off from the front of the queue.
Na Ciência da Computação uma <dfn>fila</dfn> é uma <dfn>estrutura de dados</dfn> abstrata onde itens são mantidos em ordem. Novos itens podem ser adicionados no final da fila e itens mais antigos são removidos do início da fila.
Write a function `nextInLine` which takes an array (`arr`) and a number (`item`) as arguments.
Escreva a função `nextInLine` a qual recebe um array (`arr`) e um número (`item`) como argumentos.
Add the number to the end of the array, then remove the first element of the array.
Adicione o número no final do array e então remova o primeiro elemento do array.
The `nextInLine` function should then return the element that was removed.
A função `nextInLine` deve, em seguida, retornar o elemento que foi removido.
# --hints--
`nextInLine([], 5)` should return a number.
`nextInLine([], 5)` deve retornar um número.
```js
assert.isNumber(nextInLine([], 5));
```
`nextInLine([], 1)` should return `1`
`nextInLine([], 1)` deve retonar `1`
```js
assert(nextInLine([], 1) === 1);
```
`nextInLine([2], 1)` should return `2`
`nextInLine([2], 1)` deve retornar `2`
```js
assert(nextInLine([2], 1) === 2);
```
`nextInLine([5,6,7,8,9], 1)` should return `5`
`nextInLine([5,6,7,8,9], 1)` deve retornar `5`
```js
assert(nextInLine([5, 6, 7, 8, 9], 1) === 5);
```
After `nextInLine(testArr, 10)`, `testArr[4]` should be `10`
Após `nextInLine(testArr, 10)`, `testArr[4]` deve ser `10`
```js
nextInLine(testArr, 10);

View File

@ -1,6 +1,6 @@
---
id: bd7993c9c69feddfaeb8bdef
title: Store Multiple Values in one Variable using JavaScript Arrays
title: Armazene Múltiplos Valores em uma Variável usando Arrays JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/crZQWAm'
forumTopicId: 18309
@ -9,9 +9,9 @@ dashedName: store-multiple-values-in-one-variable-using-javascript-arrays
# --description--
With JavaScript `array` variables, we can store several pieces of data in one place.
Com as variáveis de `array` em JavaScript, podemos armazenar diversos pedaços de dados em um único lugar.
You start an array declaration with an opening square bracket, end it with a closing square bracket, and put a comma between each entry, like this:
Você começa uma declaração de um array com a abertura de um colchetes, terminando com o fechamento do colchetes e colocando vírgula entre cada entrada, dessa forma:
```js
var sandwich = ["peanut butter", "jelly", "bread"]
@ -19,23 +19,23 @@ var sandwich = ["peanut butter", "jelly", "bread"]
# --instructions--
Modify the new array `myArray` so that it contains both a string and a number (in that order).
Modifique o novo array `myArray` para que contenha ambos uma string e um número (nessa ordem).
# --hints--
`myArray` should be an array.
`myArray` deve ser um array.
```js
assert(typeof myArray == 'object');
```
The first item in `myArray` should be a string.
O primeiro item de `myArray` deve ser uma string.
```js
assert(typeof myArray[0] !== 'undefined' && typeof myArray[0] == 'string');
```
The second item in `myArray` should be a number.
O segundo item de `myArray` deve ser um número.
```js
assert(typeof myArray[1] !== 'undefined' && typeof myArray[1] == 'number');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244a8
title: Storing Values with the Assignment Operator
title: Armazenando Valores com o Operador de Atribuição
challengeType: 1
videoUrl: 'https://scrimba.com/c/cEanysE'
forumTopicId: 18310
@ -9,36 +9,36 @@ dashedName: storing-values-with-the-assignment-operator
# --description--
In JavaScript, you can store a value in a variable with the <dfn>assignment</dfn> operator (`=`).
Em JavaScript, você pode armazenar um valor em uma variável com o operador de <dfn>atribuição</dfn> (`=`).
```js
myVariable = 5;
```
This assigns the `Number` value `5` to `myVariable`.
Isso atribui o valor de `Number` `5` para `myVariable`.
If there are any calculations to the right of the `=` operator, those are performed before the value is assigned to the variable on the left of the operator.
Se há qualquer cálculo a direita do operador `=`, esses cálculos são executados antes do valor ser atribuído à variável na esquerda do operador.
```js
var myVar;
myVar = 5;
```
First, this code creates a variable named `myVar`. Then, the code assigns `5` to `myVar`. Now, if `myVar` appears again in the code, the program will treat it as if it is `5`.
Primeiro, esse código cria uma variável chamada `myVar`. Em seguida, o código atribui `5` para `myVar`. Agora, se `myVar` aparece novamente no código, o programa irá tratar como se fosse `5`.
# --instructions--
Assign the value `7` to variable `a`.
Atribua o valor `7` para a variável `a`.
# --hints--
You should not change code above the specified comment.
Você não deve alterar o código acima do comentário especificado.
```js
assert(/var a;/.test(code));
```
`a` should have a value of 7.
`a` deve ter o valor de 7.
```js
assert(typeof a === 'number' && a === 7);

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c11feddfaeb4bdef
title: Subtract One Number from Another with JavaScript
title: Subtraia Um Número de Outro com JavaScript
challengeType: 1
videoUrl: 'https://scrimba.com/c/cP3yQtk'
forumTopicId: 18314
@ -9,30 +9,30 @@ dashedName: subtract-one-number-from-another-with-javascript
# --description--
We can also subtract one number from another.
Nós também podemos subtrair um número de outro.
JavaScript uses the `-` symbol for subtraction.
JavaScript usa o símbolo `-` para subtração.
**Example**
**Exemplo**
```js
myVar = 12 - 6;
```
`myVar` would have the value `6`.
`myVar` teria o valor `6`.
# --instructions--
Change the `0` so the difference is `12`.
Altere o `0` para que a variável difference seja igual a `12`.
# --hints--
The variable `difference` should be equal to 12.
A variável `difference` deve ser igual a 12.
```js
assert(difference === 12);
```
You should only subtract one number from 45.
Você só deve subtrair um número de 45.
```js
assert(/difference=45-33;?/.test(__helpers.removeWhiteSpace(code)));

View File

@ -1,6 +1,6 @@
---
id: 567af2437cbaa8c51670a16c
title: Testing Objects for Properties
title: Testando Objetos por Propriedades
challengeType: 1
videoUrl: 'https://scrimba.com/c/c6Wz4ySr'
forumTopicId: 18324
@ -9,9 +9,9 @@ dashedName: testing-objects-for-properties
# --description--
Sometimes it is useful to check if the property of a given object exists or not. We can use the `.hasOwnProperty(propname)` method of objects to determine if that object has the given property name. `.hasOwnProperty()` returns `true` or `false` if the property is found or not.
Às vezes é útil verificar se a propriedade de um determinado objeto existe ou não. Podemos usar o método de objetos `.hasOwnProperty(propname)` para determinar se aquele objeto possui o nome de propriedade fornecido. `.hasOwnProperty()` retorna `true` ou `false` se a propriedade for encontrada ou não.
**Example**
**Exemplo**
```js
var myObj = {
@ -22,15 +22,15 @@ myObj.hasOwnProperty("top");
myObj.hasOwnProperty("middle");
```
The first `hasOwnProperty` returns `true`, while the second returns `false`.
O primeiro `hasOwnProperty` retorna `true`, enquanto o segundo retorna `false`.
# --instructions--
Modify the function `checkObj` to test if an object passed to the function (`obj`) contains a specific property (`checkProp`). If the property is found, return that property's value. If not, return `"Not Found"`.
Modifique a função `checkObj` para verificar se um objeto passado para a função (`obj`) contém uma propriedade específica (`checkProp`). Se a propriedade for encontrada, retorne o valor da propriedade. Se não, retorne `"Not Found"`.
# --hints--
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` should return the string `pony`.
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "gift")` deve retornar a string `pony`.
```js
assert(
@ -38,7 +38,7 @@ assert(
);
```
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` should return the string `kitten`.
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "pet")` deve retornar a string `kitten`.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` should return the string `Not Found`.
`checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "house")` deve retornar a string `Not Found`.
```js
assert(
@ -55,19 +55,19 @@ assert(
);
```
`checkObj({city: "Seattle"}, "city")` should return the string `Seattle`.
`checkObj({city: "Seattle"}, "city")` deve retornar a string `Seattle`.
```js
assert(checkObj({ city: 'Seattle' }, 'city') === 'Seattle');
```
`checkObj({city: "Seattle"}, "district")` should return the string `Not Found`.
`checkObj({city: "Seattle"}, "district")` deve retornar a string `Not Found`.
```js
assert(checkObj({ city: 'Seattle' }, 'district') === 'Not Found');
```
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` should return the string `Not Found`.
`checkObj({pet: "kitten", bed: "sleigh"}, "gift")` deve retornar a string `Not Found`.
```js
assert(checkObj({ pet: 'kitten', bed: 'sleigh' }, 'gift') === 'Not Found');

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ba
title: Understand String Immutability
title: Entendendo a Imutabilidade das Strings
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWPVaUR'
forumTopicId: 18331
@ -9,16 +9,16 @@ dashedName: understand-string-immutability
# --description--
In JavaScript, `String` values are <dfn>immutable</dfn>, which means that they cannot be altered once created.
Em JavaScript, valores `String` são <dfn>imutáveis</dfn>, o que significa que elas não podem ser alteradas após serem criadas.
For example, the following code:
Por exemplo, o código a seguir:
```js
var myStr = "Bob";
myStr[0] = "J";
```
cannot change the value of `myStr` to `Job`, because the contents of `myStr` cannot be altered. Note that this does *not* mean that `myStr` cannot be changed, just that the individual characters of a <dfn>string literal</dfn> cannot be changed. The only way to change `myStr` would be to assign it with a new string, like this:
não é possível alterar o valor de `myStr` para `Job`, porque o conteúdo de `myStr` não pode ser alterado. Note que isso *não* significa que `myStr` não pode ser alterado, apenas que os caracteres individuais de uma <dfn>string literal</dfn> não pode ser alterado. A única forma de alterar `myStr` seria atribuindo-a com uma nova string, dessa forma:
```js
var myStr = "Bob";
@ -27,17 +27,17 @@ myStr = "Job";
# --instructions--
Correct the assignment to `myStr` so it contains the string value of `Hello World` using the approach shown in the example above.
Corrija a atribuição para `myStr` para que contenha o valor `Hello World` (string) usando a abordagem mostrada no exemplo acima.
# --hints--
`myStr` should have a value of the string `Hello World`.
`myStr` deve ter o valor da string `HelloWorld`.
```js
assert(myStr === 'Hello World');
```
You should not change the code above the specified comment.
Você não deve alterar o código acima do comentário especificado.
```js
assert(/myStr = "Jello World"/.test(code));

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c441eddfaeb5bdef
title: Understanding Boolean Values
title: Entendendo Valores Booleanos
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9Me8t4'
forumTopicId: 301176
@ -9,23 +9,23 @@ dashedName: understanding-boolean-values
# --description--
Another data type is the <dfn>Boolean</dfn>. Booleans may only be one of two values: `true` or `false`. They are basically little on-off switches, where `true` is on and `false` is off. These two states are mutually exclusive.
Outro tipo de dado é o <dfn>Boolean</dfn>. Booleanos podem ser apenas dois valores: `true` ou `false`. Eles basicamente são interruptores pequenos, onde `true` é ligado e `false` é desligado. Esses dois estados são mutuamente exclusivos.
**Note:** Boolean values are never written with quotes. The strings `"true"` and `"false"` are not Boolean and have no special meaning in JavaScript.
**Nota:** Valores booleanos nunca são escritos com aspas. As strings `"true"` e `"false"` não são Booleanos e não tem nenhum significado especial em JavaScript.
# --instructions--
Modify the `welcomeToBooleans` function so that it returns `true` instead of `false` when the run button is clicked.
Modifique a função `welcomeToBooleans` para que retorne `true` ao invés de `false` quando o botão de correr for clicado.
# --hints--
The `welcomeToBooleans()` function should return a Boolean (`true` or `false`) value.
A função `welcomeToBooleans()` deve retornar um valor Booleano (`true` ou `false`).
```js
assert(typeof welcomeToBooleans() === 'boolean');
```
`welcomeToBooleans()` should return `true`.
`welcomeToBooleans()` deve retornar `true`.
```js
assert(welcomeToBooleans() === true);

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ab
title: Understanding Case Sensitivity in Variables
title: Entendendo a Sensibilidade a Caracteres Maiúsculos e Minúsculos em Variáveis
challengeType: 1
videoUrl: 'https://scrimba.com/c/cd6GDcD'
forumTopicId: 18334
@ -9,15 +9,15 @@ dashedName: understanding-case-sensitivity-in-variables
# --description--
In JavaScript all variables and function names are case sensitive. This means that capitalization matters.
Em JavaScript todas os nomes de variáveis e funções são sensíveis a caracteres maiúsculos e minúsculos. Isso significa que a capitalização importa.
`MYVAR` is not the same as `MyVar` nor `myvar`. It is possible to have multiple distinct variables with the same name but different casing. It is strongly recommended that for the sake of clarity, you *do not* use this language feature.
`MYVAR` não é o mesmo que `MyVar` nem `myvar`. É possível ter diversas variáveis distintas com o mesmo nome mas com capitalização diferente. É extremamente recomendado pelo bem da clareza, que você *não* use esse recurso da linguagem.
**Best Practice**
**Melhores Práticas**
Write variable names in JavaScript in <dfn>camelCase</dfn>. In <dfn>camelCase</dfn>, multi-word variable names have the first word in lowercase and the first letter of each subsequent word is capitalized.
Escreva nomes de variáveis em JavaScript em <dfn>camelCase</dfn>. Em <dfn>camelCase</dfn>, nomes de variáveis com mais de uma palavra possuem a primeira palavra toda em minúscula e a primeira letra de cada palavra subsequente capitalizada.
**Examples:**
**Exemplos:**
```js
var someVariable;
@ -27,19 +27,19 @@ var thisVariableNameIsSoLong;
# --instructions--
Modify the existing declarations and assignments so their names use <dfn>camelCase</dfn>.
Modifique as declarações e atribuições existentes para que seus nomes usem <dfn>camelCase</dfn>.
Do not create any new variables.
Não crie nenhuma variável nova.
# --hints--
`studlyCapVar` should be defined and have a value of `10`.
`studlyCapVar` deve ser definido e ter um valor de `10`.
```js
assert(typeof studlyCapVar !== 'undefined' && studlyCapVar === 10);
```
`properCamelCase` should be defined and have a value of the string `A String`.
`properCamelCase` deve ser definida e ter o valor da string `A String`.
```js
assert(
@ -47,25 +47,25 @@ assert(
);
```
`titleCaseOver` should be defined and have a value of `9000`.
`titleCaseOver` deve ser definida e ter o valor de `9000`.
```js
assert(typeof titleCaseOver !== 'undefined' && titleCaseOver === 9000);
```
`studlyCapVar` should use camelCase in both declaration and assignment sections.
`studlyCapVar` deve usar camelCase em ambas as seções de declaração e atribuição.
```js
assert(code.match(/studlyCapVar/g).length === 2);
```
`properCamelCase` should use camelCase in both declaration and assignment sections.
`properCamelCase` deve usar camelCase em ambas as seções de declaração e atribuição.
```js
assert(code.match(/properCamelCase/g).length === 2);
```
`titleCaseOver` should use camelCase in both declaration and assignment sections.
`titleCaseOver` deve usar camelCase em ambas as seções de declaração e atribuição.
```js
assert(code.match(/titleCaseOver/g).length === 2);

View File

@ -1,6 +1,6 @@
---
id: 598e8944f009e646fc236146
title: Understanding Undefined Value returned from a Function
title: Entendendo Valor Undefined retornado de uma Função
challengeType: 1
videoUrl: 'https://scrimba.com/c/ce2p7cL'
forumTopicId: 301177
@ -9,9 +9,9 @@ dashedName: understanding-undefined-value-returned-from-a-function
# --description--
A function can include the `return` statement but it does not have to. In the case that the function doesn't have a `return` statement, when you call it, the function processes the inner code but the returned value is `undefined`.
Uma função pode incluir a instrução `return` mas ela não precisa fazer isso. No caso de a função não ter uma instrução `return`, quando você chamá-la, a função processa o código interno, mas o valor retornado é `undefined`.
**Example**
**Exemplo**
```js
var sum = 0;
@ -21,39 +21,38 @@ function addSum(num) {
addSum(3);
```
`addSum` is a function without a `return` statement. The function will change the global `sum` variable but the returned value of the function is `undefined`.
`addSum` é uma função sem uma instrução `return`. A função irá alterar a variável global `sum`, mas o valor retornado da função é `undefined`.
# --instructions--
Create a function `addFive` without any arguments. This function adds 5 to the `sum` variable, but its returned value is `undefined`.
Crie uma função `addFive` sem qualquer argumento. Essa função adiciona 5 à variável</code>sum`, mas o valor retornado é <code>undefined`.
# --hints--
`addFive` should be a function.
`addFive` deve ser uma função.
```js
assert(typeof addFive === 'function');
```
Once both functions have run, the `sum` should be equal to `8`.
Uma vez que ambas as funções são executadas, a `soma` deve ser igual a `8`.
```js
assert(sum === 8);
```
Returned value from `addFive` should be `undefined`.
Valor retornado de `addFive` deve ser `undefined`.
```js
assert(addFive() === undefined);
```
Inside the `addFive` function, you should add `5` to the `sum` variable.
Dentro da função `addFive`, você deve adicionar `5` à variável `sum<code>.</p>
```js
assert(
<pre><code class="js">assert(
__helpers.removeWhiteSpace(addFive.toString()).match(/sum=sum\+5|sum\+=5/)
);
```
`</pre>
# --seed--

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244aa
title: Understanding Uninitialized Variables
title: Entendendo Variáveis Não Inicializadas
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBa2JAL'
forumTopicId: 18335
@ -9,33 +9,33 @@ dashedName: understanding-uninitialized-variables
# --description--
When JavaScript variables are declared, they have an initial value of `undefined`. If you do a mathematical operation on an `undefined` variable your result will be `NaN` which means <dfn>"Not a Number"</dfn>. If you concatenate a string with an `undefined` variable, you will get a literal <dfn>string</dfn> of `undefined`.
Quando as variáveis de JavaScript são declaradas, elas têm um valor inicial de `undefined`. Se você fizer uma operação matemática em uma variável `undefined`, seu resultado será `NaN`, o que significa que <dfn>"Não é um número"</dfn>. Se você concatenar uma string com uma variável `undefined`, você receberá uma string <dfn>literal</dfn> de `undefined`.
# --instructions--
Initialize the three variables `a`, `b`, and `c` with `5`, `10`, and `"I am a"` respectively so that they will not be `undefined`.
Inicialize as três variáveis `a`, `b` e `c` com `5`, `10`, e `"Sou a"` respectivamente para que eles não sejam `undefined`.
# --hints--
`a` should be defined and evaluated to have the value of `6`.
`a` deve ser definido e avaliado para ter o valor de `6`.
```js
assert(typeof a === 'number' && a === 6);
```
`b` should be defined and evaluated to have the value of `15`.
`b` deve ser definido e avaliado para ter o valor de `15`.
```js
assert(typeof b === 'number' && b === 15);
```
`c` should not contain `undefined` and should have a value of the string `I am a String!`
`c` não deve conter `undefined` e deve ter o valor da string `eu sou uma String!`
```js
assert(!/undefined/.test(c) && c === 'I am a String!');
```
You should not change code below the specified comment.
Você não deve mudar o código abaixo do comentário especificado.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392d1
title: Updating Object Properties
title: Atualizando Propriedades do Objeto
challengeType: 1
videoUrl: 'https://scrimba.com/c/c9yEJT4'
forumTopicId: 18336
@ -9,9 +9,9 @@ dashedName: updating-object-properties
# --description--
After you've created a JavaScript object, you can update its properties at any time just like you would update any other variable. You can use either dot or bracket notation to update.
Depois de criar um objeto JavaScript, você pode atualizar suas propriedades a qualquer momento, como você atualizaria qualquer outra variável. Você pode usar notação do ponto ou colchete para atualizar.
For example, let's look at `ourDog`:
Por exemplo, vamos dar uma olhada em `ourDog`:
```js
var ourDog = {
@ -22,21 +22,21 @@ var ourDog = {
};
```
Since he's a particularly happy dog, let's change his name to the string `Happy Camper`. Here's how we update his object's name property: `ourDog.name = "Happy Camper";` or `ourDog["name"] = "Happy Camper";` Now when we evaluate `ourDog.name`, instead of getting `Camper`, we'll get his new name, `Happy Camper`.
Como ele é um cachorro particularmente feliz, vamos mudar seu nome para o texto `Happy Camper`. Veja como atualizamos a propriedade name do objeto: `ourDog.name = "Happy Camper";` ou `ourDog["name"] = "Happy Camper";` Agora, quando avaliamos `ourDog.name`, em vez de obter `Camper`, teremos seu novo nome, `Happy Camper`.
# --instructions--
Update the `myDog` object's name property. Let's change her name from `Coder` to `Happy Coder`. You can use either dot or bracket notation.
Atualize a propriedade name do objeto `myDog`. Vamos alterar o valor da propriedade name dela de `Coder` para `Happy Coder`. Você pode usar notação de ponto ou de colchetes.
# --hints--
You should update `myDog`'s `name` property to equal the string `Happy Coder`.
Você deve atualizar a propriedade `name` de `myDog` para ser igual a `Happy Coder`.
```js
assert(/happy coder/gi.test(myDog.name));
```
You should not edit the `myDog` definition.
Você não deve editar a definição de `myDog`.
```js
assert(/"name": "Coder"/.test(code));

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c549eddfaeb5bdef
title: Use Bracket Notation to Find the First Character in a String
title: Use Notação de Colchetes para Encontrar o Primeiro Caractere em uma String
challengeType: 1
videoUrl: 'https://scrimba.com/c/ca8JwhW'
forumTopicId: 18341
@ -9,36 +9,36 @@ dashedName: use-bracket-notation-to-find-the-first-character-in-a-string
# --description--
<dfn>Bracket notation</dfn> is a way to get a character at a specific index within a string.
<dfn>Notação de Colchetes</dfn> é uma forma de pegar um caractere no índice especificado dentro de uma string.
Most modern programming languages, like JavaScript, don't start counting at 1 like humans do. They start at 0. This is referred to as <dfn>Zero-based</dfn> indexing.
A maioria das linguagens de programações modernas, como JavaScript, não começa contando do 1 como humanos fazem. Eles começam no 0. Isso é referido como indexação <dfn>baseada em zero</dfn>.
For example, the character at index 0 in the word `Charles` is `C`. So if `var firstName = "Charles"`, you can get the value of the first letter of the string by using `firstName[0]`.
Por exemplo, o caractere no índice 0 da palavra `Charles` é `C`. Então se `var firstName = "Charles"`, você pode pegar o valor da primeira letra da string usando `firstName[0]`.
Example:
Exemplo:
```js
var firstName = "Charles";
var firstLetter = firstName[0];
```
`firstLetter` would have a value of the string `C`.
`firstLetter` teria o valor da string `C`.
# --instructions--
Use bracket notation to find the first character in the `lastName` variable and assign it to `firstLetterOfLastName`.
Use notação de colchetes para encontrar o primeiro caractere na variável `lastName` e atribua a letra para a variável `firstLetterOfLastName`.
**Hint:** Try looking at the example above if you get stuck.
**Dica:** Tente olhar o exemplo acima se você ficar travado.
# --hints--
The `firstLetterOfLastName` variable should have the value of `L`.
A variável `firstLetterOfLastName` deve ter o valor de `L`.
```js
assert(firstLetterOfLastName === 'L');
```
You should use bracket notation.
Você deve usar a notação de colchetes.
```js
assert(code.match(/firstLetterOfLastName\s*?=\s*?lastName\[.*?\]/));

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c451eddfaeb5bdef
title: Use Bracket Notation to Find the Last Character in a String
title: Use Notação de Colchetes para Encontrar o Último Caractere em uma String
challengeType: 1
videoUrl: 'https://scrimba.com/c/cBZQGcv'
forumTopicId: 18342
@ -9,34 +9,34 @@ dashedName: use-bracket-notation-to-find-the-last-character-in-a-string
# --description--
In order to get the last letter of a string, you can subtract one from the string's length.
Em ordem para pegar a última letra de uma string, você pode subtrair um do tamanho da string.
For example, if `var firstName = "Ada"`, you can get the value of the last letter of the string by using `firstName[firstName.length - 1]`.
Por exemplo, se `var firstName = "Ada"`, você pode pegar o valor da última letra da string ao usar `firstName[firstName.length - 1]`.
Example:
Exemplo:
```js
var firstName = "Ada";
var lastLetter = firstName[firstName.length - 1];
```
`lastLetter` would have a value of the string `a`.
`lastLetter` teria o valor da string `a`.
# --instructions--
Use <dfn>bracket notation</dfn> to find the last character in the `lastName` variable.
Use <dfn>notação de colchetes</dfn> para descobrir o último caracter na variável `lastName`.
**Hint:** Try looking at the example above if you get stuck.
**Dica:** Tente olhar o exemplo acima se você ficar travado.
# --hints--
`lastLetterOfLastName` should be the letter `e`.
`lastLetterOfLastName` deve ser a letra `e`.
```js
assert(lastLetterOfLastName === 'e');
```
You should use `.length` to get the last letter.
Você deve usar `.length` para pegar a última letra.
```js
assert(code.match(/\.length/g).length > 0);

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c450eddfaeb5bdef
title: Use Bracket Notation to Find the Nth Character in a String
title: Use Notação de Colchetes para Encontrar o Nº Caractere em uma String
challengeType: 1
videoUrl: 'https://scrimba.com/c/cWPVJua'
forumTopicId: 18343
@ -9,34 +9,34 @@ dashedName: use-bracket-notation-to-find-the-nth-character-in-a-string
# --description--
You can also use <dfn>bracket notation</dfn> to get the character at other positions within a string.
Você também pode usar <dfn>notação de colchetes</dfn> para pegar caracteres em outras posições em uma string.
Remember that computers start counting at `0`, so the first character is actually the zeroth character.
Lembre-se que computadores começam contando do `0`, então o primeiro caractere é na verdade o caractere na posição 0.
Example:
Exemplo:
```js
var firstName = "Ada";
var secondLetterOfFirstName = firstName[1];
```
`secondLetterOfFirstName` would have a value of the string `d`.
`secondLetterOfFirstName` teria o valor da string `d`.
# --instructions--
Let's try to set `thirdLetterOfLastName` to equal the third letter of the `lastName` variable using bracket notation.
Vamos tentar definir `thirdLetterOfLastName` para ser igual a terceira letra da variável `lastName` usando notação de colchetes.
**Hint:** Try looking at the example above if you get stuck.
**Dica:** Tente olhar o exemplo acima se você ficar travado.
# --hints--
The `thirdLetterOfLastName` variable should have the value of `v`.
A variável `thirdLetterOfLastName` deve ter o valor de `v`.
```js
assert(thirdLetterOfLastName === 'v');
```
You should use bracket notation.
Você deve usar notação de colchetes.
```js
assert(code.match(/thirdLetterOfLastName\s*?=\s*?lastName\[.*?\]/));

View File

@ -1,6 +1,6 @@
---
id: bd7123c9c452eddfaeb5bdef
title: Use Bracket Notation to Find the Nth-to-Last Character in a String
title: Use Notação de Colchetes para Descobrir o Nº Antes do Ultimo em uma String
challengeType: 1
videoUrl: 'https://scrimba.com/c/cw4vkh9'
forumTopicId: 18344
@ -9,34 +9,34 @@ dashedName: use-bracket-notation-to-find-the-nth-to-last-character-in-a-string
# --description--
You can use the same principle we just used to retrieve the last character in a string to retrieve the Nth-to-last character.
Você pode usar o mesmo princípio que nós acabamos de usar para recuperar o último caractere em uma string, para recuperar o Nº antes do último caractere.
For example, you can get the value of the third-to-last letter of the `var firstName = "Augusta"` string by using `firstName[firstName.length - 3]`
Por exemplo, você pode pegar o valor da antepenúltima letra da string `var fistName = "Augusta` usando `firstName[firstName.length -3]`
Example:
Exemplo:
```js
var firstName = "Augusta";
var thirdToLastLetter = firstName[firstName.length - 3];
```
`thirdToLastLetter` would have a value of the string `s`.
`thirdToLastLetter` teria o valor da string `s`.
# --instructions--
Use <dfn>bracket notation</dfn> to find the second-to-last character in the `lastName` string.
Use <dfn>notação de colchetes</dfn> para descobrir o penúltimo caractere na string `lastName`.
**Hint:** Try looking at the example above if you get stuck.
**Dica:** Tente olhar o exemplo acima se você ficar travado.
# --hints--
`secondToLastLetterOfLastName` should be the letter `c`.
`secondToLastLetterOfLastName` deve ser a letra `c`.
```js
assert(secondToLastLetterOfLastName === 'c');
```
You should use `.length` to get the second last letter.
Você deve usar `.length` para pegar a penúltima letra.
```js
assert(code.match(/\.length/g).length > 0);

View File

@ -1,6 +1,6 @@
---
id: cf1111c1c12feddfaeb3bdef
title: Use Conditional Logic with If Statements
title: Use Lógica Condicional com Instruções If
challengeType: 1
videoUrl: 'https://scrimba.com/c/cy87mf3'
forumTopicId: 18348
@ -9,15 +9,15 @@ dashedName: use-conditional-logic-with-if-statements
# --description--
`If` statements are used to make decisions in code. The keyword `if` tells JavaScript to execute the code in the curly braces under certain conditions, defined in the parentheses. These conditions are known as `Boolean` conditions and they may only be `true` or `false`.
Instruções `If` são usadas para tomar decisões no código. A palavra-chave `if` diz ao JavaScript para executar o código nas chaves sob certas condições, definidas nos parênteses. Essas condições são conhecidas como condições `Boolean` e elas só podem ser `true` ou `false`.
When the condition evaluates to `true`, the program executes the statement inside the curly braces. When the Boolean condition evaluates to `false`, the statement inside the curly braces will not execute.
Quando a condição for `true`, o programa executara as instruções dentro das chaves. Quando a condição booleana for `false`, as instruções dentro das chaves não serão executadas.
**Pseudocode**
**Pseudocódigo**
<blockquote>if (<i>condition is true</i>) {<br>  <i>statement is executed</i><br>}</blockquote>
<blockquote>if (<i>condição é verdadeira</i>) {<br><i>instrução é executada</i><br>}</blockquote>
**Example**
**Exemplo**
```js
function test (myCondition) {
@ -30,41 +30,41 @@ test(true);
test(false);
```
`test(true)` returns the string `It was true`, and `test(false)` returns the string `It was false`.
`test(true)` retorna a string `It was true` e `test(false)` retorna a string `It was false`.
When `test` is called with a value of `true`, the `if` statement evaluates `myCondition` to see if it is `true` or not. Since it is `true`, the function returns `It was true`. When we call `test` with a value of `false`, `myCondition` is *not* `true` and the statement in the curly braces is not executed and the function returns `It was false`.
Quando `test` é chamado com o valor `true`, a instrução `if` avalia `myCondition` para verificar se é `true` ou não. Já que é `true`, a função retorna `It was true`. Quando chamamos `test` com um valor de `false`, `myCondition` *não é* `true` e a instrução nas chaves não é executada e a função retorna `It was false`.
# --instructions--
Create an `if` statement inside the function to return `Yes, that was true` if the parameter `wasThatTrue` is `true` and return `No, that was false` otherwise.
Crie uma instrução `if` dentro da função para retornar `Yes, that was true` se o parâmetro `wasThatTrue` for `true` e retorne `No, that was false` caso contrário.
# --hints--
`trueOrFalse` should be a function
`trueOrFalse` deve ser uma função
```js
assert(typeof trueOrFalse === 'function');
```
`trueOrFalse(true)` should return a string
`trueOrFalse(true)` deve retornar uma string
```js
assert(typeof trueOrFalse(true) === 'string');
```
`trueOrFalse(false)` should return a string
`trueOrFalse(false)` deve retornar uma string
```js
assert(typeof trueOrFalse(false) === 'string');
```
`trueOrFalse(true)` should return the string `Yes, that was true`
`trueOrFalse(true)` deve retornar a string `Yes, that was true`
```js
assert(trueOrFalse(true) === 'Yes, that was true');
```
`trueOrFalse(false)` should return the string `No, that was false`
`trueOrFalse(false)` deve retornar a string `No, that was false`
```js
assert(trueOrFalse(false) === 'No, that was false');

View File

@ -1,6 +1,6 @@
---
id: 587d7b7e367417b2b2512b21
title: Use Multiple Conditional (Ternary) Operators
title: Usar Operadores de Múltiplas Condições (Ternário)
challengeType: 1
videoUrl: 'https://scrimba.com/c/cyWJBT4'
forumTopicId: 301179
@ -9,9 +9,9 @@ dashedName: use-multiple-conditional-ternary-operators
# --description--
In the previous challenge, you used a single conditional operator. You can also chain them together to check for multiple conditions.
No desafio anterior, você usou um único operador condicional. Você também pode encadear eles juntos para verificar por múltiplas condições.
The following function uses `if`, `else if`, and `else` statements to check multiple conditions:
A seguinte função usa as instruções `if`, `else if` e `else` para verificar múltiplas condições:
```js
function findGreaterOrEqual(a, b) {
@ -27,7 +27,7 @@ function findGreaterOrEqual(a, b) {
}
```
The above function can be re-written using multiple conditional operators:
A função acima pode ser rescrita usando operadores de múltiplas condições (operador ternário):
```js
function findGreaterOrEqual(a, b) {
@ -37,7 +37,7 @@ function findGreaterOrEqual(a, b) {
}
```
It is considered best practice to format multiple conditional operators such that each condition is on a separate line, as shown above. Using multiple conditional operators without proper indentation may make your code hard to read. For example:
É considerado a melhor prática para formatar operadores de múltiplas condições, tal que cada condição está em uma linha separada, como mostrada acima. Usando operadores de múltiplas condições sem a indentação adequada pode dificultar a leitura do seu código. Por exemplo:
```js
function findGreaterOrEqual(a, b) {
@ -47,29 +47,29 @@ function findGreaterOrEqual(a, b) {
# --instructions--
In the `checkSign` function, use multiple conditional operators - following the recommended format used in `findGreaterOrEqual` - to check if a number is positive, negative or zero. The function should return `positive`, `negative` or `zero`.
Na função `checkSign`, use operadores de múltiplas condições - seguindo o formato recomendado usado em `findGreaterOrEqual` - para verificar se um número é positivo, negativo ou zero. A função deve retornar `positive`, `negative` ou `zero`.
# --hints--
`checkSign` should use multiple conditional operators
`checkSign` deve usar operadores de múltiplas condições
```js
assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?\s*?\?\s*?.+?\s*?:\s*?.+?/gi.test(code));
```
`checkSign(10)` should return the string `positive`. Note that capitalization matters
`checkSign(10)` deve retornar a string `positive`. Observe que a capitalização importa
```js
assert(checkSign(10) === 'positive');
```
`checkSign(-12)` should return the string `negative`. Note that capitalization matters
`checkSign(-12)` deve retornar a string `negative`. Observe que a capitalização importa
```js
assert(checkSign(-12) === 'negative');
```
`checkSign(0)` should return the string `zero`. Note that capitalization matters
`checkSign(0)` deve retornar a string `zero`. Observe que a capitalização importa
```js
assert(checkSign(0) === 'zero');

View File

@ -1,6 +1,6 @@
---
id: 5cd9a70215d3c4e65518328f
title: Use Recursion to Create a Countdown
title: Use Recursividade para Criar uma Contagem Regressiva
challengeType: 1
forumTopicId: 305925
dashedName: use-recursion-to-create-a-countdown
@ -8,11 +8,11 @@ dashedName: use-recursion-to-create-a-countdown
# --description--
In a [previous challenge](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion), you learned how to use recursion to replace a `for` loop. Now, let's look at a more complex function that returns an array of consecutive integers starting with `1` through the number passed to the function.
Em um [desafio anterior](/learn/javascript-algorithms-and-data-structures/basic-javascript/replace-loops-using-recursion), você aprendeu como usar recursividade para substituir laços `for`. Agora, vamos analisar uma função mais complexa, a qual retorna um array de inteiros consecutivos começando com `1` até o número passado para a função.
As mentioned in the previous challenge, there will be a <dfn>base case</dfn>. The base case tells the recursive function when it no longer needs to call itself. It is a simple case where the return value is already known. There will also be a <dfn>recursive call</dfn> which executes the original function with different arguments. If the function is written correctly, eventually the base case will be reached.
Como mencionado no desafio anterior, haverá um <dfn>caso base</dfn>. O caso base diz a função recursiva quando ela não precisa mais chamar a si. É um simples caso onde o valor de retorno já é conhecido. Também haverá uma <dfn>chamada recursiva</dfn> a qual executa a função original com argumentos diferentes. Se a função for escrita corretamente, eventualmente o caso base será alcançado.
For example, say you want to write a recursive function that returns an array containing the numbers `1` through `n`. This function will need to accept an argument, `n`, representing the final number. Then it will need to call itself with progressively smaller values of `n` until it reaches `1`. You could write the function as follows:
Por exemplo, vamos dizer que você quer escrever uma função recursiva que retorna um array contendo os números de `1` até `n`. Essa função precisará aceitar um argumento, `n`, representando o número final. Então ela precisará chamar a si mesmo como valores progressivamente menores de `n` até que alcance `1`. Você poderia escrever a função da seguinte forma:
```javascript
function countup(n) {
@ -27,35 +27,35 @@ function countup(n) {
console.log(countup(5));
```
The value `[1, 2, 3, 4, 5]` will be displayed in the console.
O valor `[1, 2, 3, 4, 5]` será exibido no console.
At first, this seems counterintuitive since the value of `n` *decreases*, but the values in the final array are *increasing*. This happens because the push happens last, after the recursive call has returned. At the point where `n` is pushed into the array, `countup(n - 1)` has already been evaluated and returned `[1, 2, ..., n - 1]`.
Inicialmente, isso se parece contra-intuitivo já que o valor de `n` *diminui*, mas os valores no array final estão *em ordem crescente*. Isso acontece porque a adição no array (push) acontece por último, após a chamada recursiva ter retornado. No ponto onde `n` é adicionado ao array, `countup(n - 1)` já foi avaliado e retornou `[1, 2, ..., n -1]`.
# --instructions--
We have defined a function called `countdown` with one parameter (`n`). The function should use recursion to return an array containing the integers `n` through `1` based on the `n` parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function with `n = 5` should return the array `[5, 4, 3, 2, 1]`. Your function must use recursion by calling itself and must not use loops of any kind.
Definimos uma função chamada `countdown` com um parâmetro (`n`). A função deve usar recursividade para retornar um array contendo inteiros `n` até `1` baseado no parâmetro `n`. Se a função é chamada com um número menor que 1, a função deve retornar um array vazio. Por exemplo, chamando essa função com `n = 5` deve retornar o array `[5, 4, 3, 2, 1]`. Sua função precisa usar recursividade ao chamar ela mesma e não deve usar laços de qualquer tipo.
# --hints--
`countdown(-1)` should return an empty array.
`countdown(-1)` deve retornar um array vazio.
```js
assert.isEmpty(countdown(-1));
```
`countdown(10)` should return `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`
`countdown(10)` deve retornar `[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]`
```js
assert.deepStrictEqual(countdown(10), [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
```
`countdown(5)` should return `[5, 4, 3, 2, 1]`
`countdown(5)` deve retornar `[5, 4, 3, 2, 1]`
```js
assert.deepStrictEqual(countdown(5), [5, 4, 3, 2, 1]);
```
Your code should not rely on any kind of loops (`for`, `while` or higher order functions such as `forEach`, `map`, `filter`, and `reduce`).
Seu código não deve depender de nenhum tipo de laço (`for`, `while` ou outras funções superiores como `forEach`, `map`, `filter` e `reduce`).
```js
assert(
@ -63,7 +63,7 @@ assert(
);
```
You should use recursion to solve this problem.
Você deve usar recursividade para resolver esse problema.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5cc0bd7a49b71cb96132e54c
title: Use Recursion to Create a Range of Numbers
title: Use Recursividade para Criar um Intervalo de Números
challengeType: 1
forumTopicId: 301180
dashedName: use-recursion-to-create-a-range-of-numbers
@ -8,21 +8,21 @@ dashedName: use-recursion-to-create-a-range-of-numbers
# --description--
Continuing from the previous challenge, we provide you another opportunity to create a recursive function to solve a problem.
Continuando do desafio anterior, nós o fornecemos outra oportunidade para criar uma função recursiva para resolver um problema.
# --instructions--
We have defined a function named `rangeOfNumbers` with two parameters. The function should return an array of integers which begins with a number represented by the `startNum` parameter and ends with a number represented by the `endNum` parameter. The starting number will always be less than or equal to the ending number. Your function must use recursion by calling itself and not use loops of any kind. It should also work for cases where both `startNum` and `endNum` are the same.
Definimos uma função chamada `rangeOfNumbers` com dois parâmetros. A função deve retornar um array de inteiros a qual começa com um número representado pelo parâmetro `startNum` e terminar com um número representado pelo parâmetro `endNum`. O número inicial sempre será menor ou igual ao número final. Sua função precisa usar recursividade ao chamar ela mesma e não depender de nenhum tipo de laço. Também deve funcionar para casos onde ambos `startNum` e `endNum` forem o mesmo.
# --hints--
Your function should return an array.
Sua função deve retornar um array.
```js
assert(Array.isArray(rangeOfNumbers(5, 10)));
```
Your code should not use any loop syntax (`for` or `while` or higher order functions such as `forEach`, `map`, `filter`, or `reduce`).
Seu código não deve depender de nenhum laço (`for` ou `while` ou funções de ordem superior como as funções `forEach`, `map`, `filter` ou `reduce`).
```js
assert(
@ -30,7 +30,7 @@ assert(
);
```
`rangeOfNumbers` should use recursion (call itself) to solve this challenge.
`rangeOfNumbers` deve usar recursão (chamar a si) para resolver este desafio.
```js
assert(
@ -38,19 +38,19 @@ assert(
);
```
`rangeOfNumbers(1, 5)` should return `[1, 2, 3, 4, 5]`.
`rangeOfNumbers(1, 5)` deve retornar `[1, 2, 3, 4, 5]`.
```js
assert.deepStrictEqual(rangeOfNumbers(1, 5), [1, 2, 3, 4, 5]);
```
`rangeOfNumbers(6, 9)` should return `[6, 7, 8, 9]`.
`rangeOfNumbers(6, 9)` deve retornar `[6, 7, 8, 9]`.
```js
assert.deepStrictEqual(rangeOfNumbers(6, 9), [6, 7, 8, 9]);
```
`rangeOfNumbers(4, 4)` should return `[4]`.
`rangeOfNumbers(4, 4)` deve retornar `[4]`.
```js
assert.deepStrictEqual(rangeOfNumbers(4, 4), [4]);

View File

@ -1,6 +1,6 @@
---
id: 587d7b7e367417b2b2512b24
title: Use the Conditional (Ternary) Operator
title: Use o Operador Condicional (ternário)
challengeType: 1
forumTopicId: 301181
dashedName: use-the-conditional-ternary-operator
@ -8,11 +8,11 @@ dashedName: use-the-conditional-ternary-operator
# --description--
The <dfn>conditional operator</dfn>, also called the <dfn>ternary operator</dfn>, can be used as a one line if-else expression.
O <dfn>operador condicional</dfn>, também chamado de <dfn>operador ternário</dfn>, pode ser usado como uma expressão if-else de uma linha.
The syntax is `a ? b : c`, where `a` is the condition, `b` is the code to run when the condition returns `true`, and `c` is the code to run when the condition returns `false`.
A sintaxe é `a ? b : c`, onde `a` é a condição, `b` é o código executado quando a condição retorna `true` e `c` é o código executado quando a condição retorna `false`.
The following function uses an `if/else` statement to check a condition:
A função a seguir usa a instrução `if/else` para verificar uma condição:
```js
function findGreater(a, b) {
@ -25,7 +25,7 @@ function findGreater(a, b) {
}
```
This can be re-written using the conditional operator:
Isto pode ser reescrito usando o operador condicional:
```js
function findGreater(a, b) {
@ -35,29 +35,29 @@ function findGreater(a, b) {
# --instructions--
Use the conditional operator in the `checkEqual` function to check if two numbers are equal or not. The function should return either the string `Equal` or the string `Not Equal`.
Use o operador condicional na função `checkEqual` para verificar se dois números são iguais ou não. A função deve retornar ou a string `Equal` ou a string `Not Equal`.
# --hints--
`checkEqual` should use the conditional operator
`checkEqual` deve usar o operador condicional
```js
assert(/.+?\s*?\?\s*?.+?\s*?:\s*?.+?/.test(code));
```
`checkEqual(1, 2)` should return the string `Not Equal`
`checkEqual(1, 2)` deve retornar a string `Not Equal`
```js
assert(checkEqual(1, 2) === 'Not Equal');
```
`checkEqual(1, 1)` should return the string `Equal`
`checkEqual(1, 1)` deve retornar a string `Equal`
```js
assert(checkEqual(1, 1) === 'Equal');
```
`checkEqual(1, -1)` should return the string `Not Equal`
`checkEqual(1, -1)` deve retornar a string `Not Equal`
```js
assert(checkEqual(1, -1) === 'Not Equal');

View File

@ -1,6 +1,6 @@
---
id: 587d7b7e367417b2b2512b22
title: Use the parseInt Function with a Radix
title: Use a Função parseInt com um Radix
challengeType: 1
videoUrl: 'https://scrimba.com/c/c6K4Kh3'
forumTopicId: 301182
@ -9,53 +9,53 @@ dashedName: use-the-parseint-function-with-a-radix
# --description--
The `parseInt()` function parses a string and returns an integer. It takes a second argument for the radix, which specifies the base of the number in the string. The radix can be an integer between 2 and 36.
A função `parseInt()` analisa uma string e retorna um inteiro. É preciso um segundo argumento para o radix, que especifica a base do número na string. O radix pode ser um inteiro entre 2 e 36.
The function call looks like:
A chamada da função se parece com:
```js
parseInt(string, radix);
```
And here's an example:
E aqui um exemplo:
```js
var a = parseInt("11", 2);
```
The radix variable says that `11` is in the binary system, or base 2. This example converts the string `11` to an integer `3`.
A variável radix diz que `11` está no sistema binário, ou base 2. Esse exemplo converte a string `11` para um inteiro `3`.
# --instructions--
Use `parseInt()` in the `convertToInteger` function so it converts a binary number to an integer and returns it.
Use `parseInt()` na função `convertToInteger` para que ela converta um número binário em um inteiro e o retorne.
# --hints--
`convertToInteger` should use the `parseInt()` function
`convertToInteger` deve usar a função `parseInt()`
```js
assert(/parseInt/g.test(code));
```
`convertToInteger("10011")` should return a number
`convertToInteger("10011")` deve retornar um número
```js
assert(typeof convertToInteger('10011') === 'number');
```
`convertToInteger("10011")` should return 19
`convertToInteger("10011")` deve retornar 19
```js
assert(convertToInteger('10011') === 19);
```
`convertToInteger("111001")` should return 57
`convertToInteger("111001")` deve retornar 57
```js
assert(convertToInteger('111001') === 57);
```
`convertToInteger("JamesBond")` should return `NaN`
`convertToInteger("JamesBond")` deve retornar `NaN`
```js
assert.isNaN(convertToInteger('JamesBond'));

View File

@ -1,6 +1,6 @@
---
id: 587d7b7e367417b2b2512b23
title: Use the parseInt Function
title: Use a função parseInt
challengeType: 1
videoUrl: 'https://scrimba.com/c/cm83LSW'
forumTopicId: 301183
@ -9,45 +9,45 @@ dashedName: use-the-parseint-function
# --description--
The `parseInt()` function parses a string and returns an integer. Here's an example:
A função `parseInt()` analisa uma string e retorna um inteiro. Aqui está um exemplo:
```js
var a = parseInt("007");
```
The above function converts the string `007` to the integer `7`. If the first character in the string can't be converted into a number, then it returns `NaN`.
A função acima converte a string `007` para o inteiro `7`. Se o primeiro caractere na string não pode ser convertido em um número, então ele retorna `NaN`.
# --instructions--
Use `parseInt()` in the `convertToInteger` function so it converts the input string `str` into an integer, and returns it.
Use `parseInt()` na função `convertToInteger` para que ela converta a string de entrada `str` em um inteiro e a retorne.
# --hints--
`convertToInteger` should use the `parseInt()` function
`convertToInteger` deve usar a função `parseInt()`
```js
assert(/parseInt/g.test(code));
```
`convertToInteger("56")` should return a number
`convertToInteger("56")` deve retornar um número
```js
assert(typeof convertToInteger('56') === 'number');
```
`convertToInteger("56")` should return 56
`convertToInteger("56")` deve retornar 56
```js
assert(convertToInteger('56') === 56);
```
`convertToInteger("77")` should return 77
`convertToInteger("77")` deve retornar 77
```js
assert(convertToInteger('77') === 77);
```
`convertToInteger("JamesBond")` should return `NaN`
`convertToInteger("JamesBond")` deve retornar `NaN`
```js
assert.isNaN(convertToInteger('JamesBond'));

View File

@ -1,6 +1,6 @@
---
id: 56533eb9ac21ba0edf2244ca
title: Using Objects for Lookups
title: Usando Objetos para Pesquisas
challengeType: 1
videoUrl: 'https://scrimba.com/c/cdBk8sM'
forumTopicId: 18373
@ -9,9 +9,9 @@ dashedName: using-objects-for-lookups
# --description--
Objects can be thought of as a key/value storage, like a dictionary. If you have tabular data, you can use an object to lookup values rather than a `switch` statement or an `if/else` chain. This is most useful when you know that your input data is limited to a certain range.
Objetos podem ser pensados como armazenamento de chave/valor, como um dicionário. Se você tem um dado tabular, você pode usar um objeto para pesquisar valores ao invés de uma instrução `switch` ou uma cadeia de `if/else`. Isso é mais útil quando você sabe que o seu dado de entrada é limitado para um certo intervalo.
Here is an example of a simple reverse alphabet lookup:
Aqui está um exemplo de uma simples pesquisa reversa no alfabeto:
```js
var alpha = {
@ -31,63 +31,63 @@ var value = 2;
alpha[value];
```
`alpha[2]` is the string `Y`, `alpha[24]` is the string `C`, and `alpha[value]` is the string `Y`.
`alpha[2]` é a string `Y`, `alpha[24]` é a string `C` e `alpha[value]` é a string `Y`.
# --instructions--
Convert the switch statement into an object called `lookup`. Use it to look up `val` and assign the associated string to the `result` variable.
Converta a instrução switch em um objeto chamado `lookup`. Use ele para pesquisar por `val` e atribua a string associada para a variável `result`.
# --hints--
`phoneticLookup("alpha")` should equal the string `Adams`
`phoneticLookup("alpha")` deve ser igual a string `Adams`
```js
assert(phoneticLookup('alpha') === 'Adams');
```
`phoneticLookup("bravo")` should equal the string `Boston`
`phoneticLookup("bravo")` deve ser igual a string `Boston`
```js
assert(phoneticLookup('bravo') === 'Boston');
```
`phoneticLookup("charlie")` should equal the string `Chicago`
`phoneticLookup("charlie")` deve ser igual a string `Chicago`
```js
assert(phoneticLookup('charlie') === 'Chicago');
```
`phoneticLookup("delta")` should equal the string `Denver`
`phoneticLookup("delta")` deve ser igual a string `Denver`
```js
assert(phoneticLookup('delta') === 'Denver');
```
`phoneticLookup("echo")` should equal the string `Easy`
`phoneticLookup("echo")` deve ser igual a string `Easy`
```js
assert(phoneticLookup('echo') === 'Easy');
```
`phoneticLookup("foxtrot")` should equal the string `Frank`
`phoneticLookup("foxtrot")` deve ser igual a string `Frank`
```js
assert(phoneticLookup('foxtrot') === 'Frank');
```
`phoneticLookup("")` should equal `undefined`
`phoneticLookup("")` deve ser igual a `undefined`
```js
assert(typeof phoneticLookup('') === 'undefined');
```
You should not modify the `return` statement
Você não deve modificar a instrução `return`
```js
assert(code.match(/return\sresult;/));
```
You should not use `case`, `switch`, or `if` statements
Você não deve usar as instruções `case`, `switch` ou `if`
```js
assert(

View File

@ -9,11 +9,11 @@ dashedName: word-blanks
# --description--
We will now use our knowledge of strings to build a "[Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)" style word game we're calling "Word Blanks". You will create an (optionally humorous) "Fill in the Blanks" style sentence.
Nós iremos agora usar nosso conhecimento de strings para criar um "[Mad Libs](https://en.wikipedia.org/wiki/Mad_Libs)" estilo de jogo de palavras que chamamos de "Palavras em Branco". Você irá criar uma frase no estilo "Preencha os Espaços em Branco" (opcionalmente humorosa).
In a "Mad Libs" game, you are provided sentences with some missing words, like nouns, verbs, adjectives and adverbs. You then fill in the missing pieces with words of your choice in a way that the completed sentence makes sense.
Em um jogo "Mad Libs", você recebe frases com algumas palavras faltando, como substantivos, verbos, adjetivos e advérbios. Você então irá preencher os pedaços faltantes com palavras de sua escolha em uma forma que a frase completa faça sentido.
Consider this sentence - It was really **\_\_\_\_**, and we **\_\_\_\_** ourselves **\_\_\_\_**. This sentence has three missing pieces- an adjective, a verb and an adverb, and we can add words of our choice to complete it. We can then assign the completed sentence to a variable as follows:
Considere a frase - Era realmente **\_\_\_\_** e nós **\_\_\_\_** nós mesmos **\_\_\_\_**. Essa sentença possui três pedaços faltando - um adjetivo, um verbo e um advérbio, e nós podemos adicionar palavras de nossa escolha para completar. Em seguida, podemos atribuir a frase completa para uma variável como se segue:
```js
var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves " + "silly" + ".";
@ -21,21 +21,21 @@ var sentence = "It was really " + "hot" + ", and we " + "laughed" + " ourselves
# --instructions--
In this challenge, we provide you with a noun, a verb, an adjective and an adverb. You need to form a complete sentence using words of your choice, along with the words we provide.
Nesse desafio, nós fornecemos a você um substantivo, um verbo, um adjetivo e um advérbio. Você precisar formular uma frase completa usando palavras de sua escolha, junto com as palavras que nós fornecemos.
You will need to use the string concatenation operator `+` to build a new string, using the provided variables: `myNoun`, `myAdjective`, `myVerb`, and `myAdverb`. You will then assign the formed string to the `wordBlanks` variable. You should not change the words assigned to the variables.
Você precisará usar o operador de concatenação de string `+` para criar uma nova string, usando as variáveis fornecidas: `myNoun`, `myAdjective`, `myVerb` e `myAdverb`. Em seguida, você atribuirá a string formada para a variável `wordBlanks`. Você não deve alterar as palavras atribuídas às variáveis.
You will also need to account for spaces in your string, so that the final sentence has spaces between all the words. The result should be a complete sentence.
Você também precisará se responsabilizar por espaços em sua string, para que na frase final possua espaços entre todas as palavras. O resultado não deve ser uma frase completa.
# --hints--
`wordBlanks` should be a string.
`wordBlanks` deve ser uma string.
```js
assert(typeof wordBlanks === 'string');
```
You should not change the values assigned to `myNoun`, `myVerb`, `myAdjective` or `myAdverb`.
Você não deve alterar os valores atribuídos a `myNoun`, `myVerb`, `myAdjective` ou `myAdverb`.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
You should not directly use the values `dog`, `ran`, `big`, or `quickly` to create `wordBlanks`.
Você não deve usar diretamente os valores `dog`, `ran`, `big` ou `quickly` para criar `wordBlanks`.
```js
const newCode = removeAssignments(code);
@ -58,7 +58,7 @@ assert(
);
```
`wordBlanks` should contain all of the words assigned to the variables `myNoun`, `myVerb`, `myAdjective` and `myAdverb` separated by non-word characters (and any additional words in your madlib).
`wordBlanks` deve conter todas as palavras atribuídas às variáveis `myNoun`, `myVerb`, `myAdjective` e `myAdverb` separadas por caracteres que não sejam palavras (e qualquer palavra adicional na sua madlib).
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 56bbb991ad1ed5201cd392cf
title: Write Reusable JavaScript with Functions
title: Escreva JavaScript Reutilizável com Funções
challengeType: 1
videoUrl: 'https://scrimba.com/c/cL6dqfy'
forumTopicId: 18378
@ -9,9 +9,9 @@ dashedName: write-reusable-javascript-with-functions
# --description--
In JavaScript, we can divide up our code into reusable parts called <dfn>functions</dfn>.
Em JavaScript, nós podemos dividir nosso código em partes reutilizáveis chamadas de <dfn>functions</dfn>.
Here's an example of a function:
Aqui está um exemplo de uma função:
```js
function functionName() {
@ -19,34 +19,34 @@ function functionName() {
}
```
You can call or <dfn>invoke</dfn> this function by using its name followed by parentheses, like this: `functionName();` Each time the function is called it will print out the message `Hello World` on the dev console. All of the code between the curly braces will be executed every time the function is called.
Você pode chamar ou <dfn>invocar</dfn> essa função ao usar seu nome seguido de parênteses, da seguinte forma: `functionName();` Cada vez que a função é chamada irá imprimir no console a mensagem `Hello World`. Todo o código entre as chaves será executado toda vez que uma função for chamada.
# --instructions--
<ol>
<li>
Create a function called <code>reusableFunction</code> which prints the string <code>Hi World</code> to the dev console.
Crie uma função chamada <code>reusableFunction</code> que imprime a string <code>Hi World</code> no console.
</li>
<li>
Call the function.
Chame a função.
</li>
</ol>
# --hints--
`reusableFunction` should be a function.
`reusableFunction` deve ser uma função.
```js
assert(typeof reusableFunction === 'function');
```
If `reusableFunction` is called, it should output the string `Hi World` to the console.
Se `reusableFunction` é chamada, deve exibir no console a string `Hi World`.
```js
assert(testConsole());
```
You should call `reusableFunction` once it is defined.
Você deve chamar `reusableFunction` uma vez que for definida.
```js
const functionStr = reusableFunction && __helpers.removeWhiteSpace(reusableFunction.toString());

View File

@ -1,6 +1,6 @@
---
id: 587d7b85367417b2b2512b3a
title: Catch Arguments Passed in the Wrong Order When Calling a Function
title: Capture Argumentos Passados na Ordem Errada Quando Chamando uma Função
challengeType: 1
forumTopicId: 301184
dashedName: catch-arguments-passed-in-the-wrong-order-when-calling-a-function
@ -8,21 +8,21 @@ dashedName: catch-arguments-passed-in-the-wrong-order-when-calling-a-function
# --description--
Continuing the discussion on calling functions, the next bug to watch out for is when a function's arguments are supplied in the incorrect order. If the arguments are different types, such as a function expecting an array and an integer, this will likely throw a runtime error. If the arguments are the same type (all integers, for example), then the logic of the code won't make sense. Make sure to supply all required arguments, in the proper order to avoid these issues.
Continuando a discussão sobre chamada de funções, o próximo bug para prestar atenção é quando os argumentos de uma função são fornecidos na ordem incorreta. Se os argumentos forem de diferentes tipos, tal como uma função esperando um array e um inteiro, isso irá provavelmente lançar um erro de tempo de execução. Se os argumentos são do mesmo tipo (todos os inteiros, por exemplo), então a lógica do código não fará sentido. Certifique-se de fornecer todos os argumentos exigidos, na ordem adequada para evitar esses problemas.
# --instructions--
The function `raiseToPower` raises a base to an exponent. Unfortunately, it's not called properly - fix the code so the value of `power` is the expected 8.
A função `raiseToPower` eleva uma base para um expoente. Infelizmente, não é chamada corretamente - corrija o código para que o valor de `power` seja o esperado 8.
# --hints--
Your code should fix the variable `power` so it equals 2 raised to the 3rd power, not 3 raised to the 2nd power.
Seu código deve corrigir a variável `power` para que seja igual a 2 elevado a 3ª potência, e não 3 elevado a 2ª potência.
```js
assert(power == 8);
```
Your code should use the correct order of the arguments for the `raiseToPower` function call.
Seu código deve usar a ordem correta dos argumentos para a chamada da função `raiseToPower`.
```js
assert(code.match(/raiseToPower\(\s*?base\s*?,\s*?exp\s*?\);/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b85367417b2b2512b39
title: Catch Missing Open and Closing Parenthesis After a Function Call
title: Capture Abertura e Fechamento de Parênteses Faltantes Após uma Chamada de Função
challengeType: 1
forumTopicId: 301185
dashedName: catch-missing-open-and-closing-parenthesis-after-a-function-call
@ -8,9 +8,9 @@ dashedName: catch-missing-open-and-closing-parenthesis-after-a-function-call
# --description--
When a function or method doesn't take any arguments, you may forget to include the (empty) opening and closing parentheses when calling it. Often times the result of a function call is saved in a variable for other use in your code. This error can be detected by logging variable values (or their types) to the console and seeing that one is set to a function reference, instead of the expected value the function returns.
Quando uma função ou método não recebe nenhum parâmetro, você pode esquecer de incluir a abertura e fechamento de parênteses (vazio) ao chamá-la. Frequentemente, o resultado de uma chamada de função é salva em uma variável para outro uso em seu código. Esse erro pode ser detectado ao exibir no console os valores das variáveis (ou seus tipos) e verificar que uma variável está definida para uma referência de uma função, ao invés do valor esperado que a função retorna.
The variables in the following example are different:
As variáveis no seguinte exemplo são diferentes:
```js
function myFunction() {
@ -20,21 +20,21 @@ let varOne = myFunction;
let varTwo = myFunction();
```
Here `varOne` is the function `myFunction`, and `varTwo` is the string `You rock!`.
Aqui `varOne` é a função `myFunction` e `varTwo` é a string `You rock!`.
# --instructions--
Fix the code so the variable `result` is set to the value returned from calling the function `getNine`.
Corrija o código para que a variável `result` seja definida para o valor retornado da chamada da função `getNine`.
# --hints--
Your code should fix the variable `result` so it is set to the number that the function `getNine` returns.
Seu código deve corrigir a variável `result` para que seja definida para o número que a função `getNine` retorna.
```js
assert(result == 9);
```
Your code should call the `getNine` function.
Seu código deve chamar a função `getNine`.
```js
assert(code.match(/getNine\(\)/g).length == 2);

View File

@ -1,6 +1,6 @@
---
id: 587d7b84367417b2b2512b35
title: Catch Misspelled Variable and Function Names
title: Capture Nomes de Variáveis e Funções Com Erros Ortográficos
challengeType: 1
forumTopicId: 301186
dashedName: catch-misspelled-variable-and-function-names
@ -8,41 +8,41 @@ dashedName: catch-misspelled-variable-and-function-names
# --description--
The `console.log()` and `typeof` methods are the two primary ways to check intermediate values and types of program output. Now it's time to get into the common forms that bugs take. One syntax-level issue that fast typers can commiserate with is the humble spelling error.
Os métodos `console.log()` e `typeof` são duas formas primárias para verificar valores intermediários e tipos de saída do programa. Agora é hora entrar nas formas comuns que um bug assume. Um problema de nível de sintaxe que digitadores rápidos podem ter passado é o humilde erro de digitação incorreta.
Transposed, missing, or mis-capitalized characters in a variable or function name will have the browser looking for an object that doesn't exist - and complain in the form of a reference error. JavaScript variable and function names are case-sensitive.
Caracteres deslocados, faltando ou capitalizado erroneamente em um nome de variável ou função fará com que o navegador procure por um objeto que não existe - e reclamará na forma de um erro de referência. Variáveis e funções JavaScript são sensíveis a caracteres maiúsculos e minúsculos.
# --instructions--
Fix the two spelling errors in the code so the `netWorkingCapital` calculation works.
Corrija os dois erros de ortografia no código para que o cálculo `netWorkingCapital` funcione.
# --hints--
Check the spelling of the two variables used in the netWorkingCapital calculation, the console output should show that "Net working capital is: 2".
Verifique a ortografia das duas variáveis usadas no cálculo de netWorkingCapital, a saída do console deve mostrar que "Net working capital is: 2".
```js
assert(netWorkingCapital === 2);
```
There should be no instances of mis-spelled variables in the code.
Não deve haver instâncias de variáveis com ortografia incorretas no código.
```js
assert(!code.match(/recievables/g));
```
The `receivables` variable should be declared and used properly in the code.
A variável `receivables` deve ser declarada e usada corretamente no código.
```js
assert(code.match(/receivables/g).length == 2);
```
There should be no instances of mis-spelled variables in the code.
Não deve haver instâncias de variáveis com ortografia incorretas no código.
```js
assert(!code.match(/payable;/g));
```
The `payables` variable should be declared and used properly in the code.
A variável `payables` deve ser declarada e usada corretamente no código.
```js
assert(code.match(/payables/g).length == 2);

View File

@ -1,6 +1,6 @@
---
id: 587d7b84367417b2b2512b37
title: Catch Mixed Usage of Single and Double Quotes
title: Identificar Uso Misto de Aspas Simples e Duplas
challengeType: 1
forumTopicId: 301188
dashedName: catch-mixed-usage-of-single-and-double-quotes
@ -8,21 +8,20 @@ dashedName: catch-mixed-usage-of-single-and-double-quotes
# --description--
JavaScript allows the use of both single (`'`) and double (`"`) quotes to declare a string. Deciding which one to use generally comes down to personal preference, with some exceptions.
JavaScript nos permite o uso de ambas as aspas simples (`'<code>) e duplas (<code>"<code>) para declarar uma string. Decidir qual delas usar geralmente é uma questão de preferência pessoal, com algumas exceções.</p>
Having two choices is great when a string has contractions or another piece of text that's in quotes. Just be careful that you don't close the string too early, which causes a syntax error.
<p spaces-before="0">Ter duas opções é ótimo quando uma string possui contrações ou outros pedaços de texto que estão entre aspas. Apenas tome cuidado para que você não feche uma string muito cedo, o que causa erro de sintaxe.</p>
Here are some examples of mixing quotes:
<p spaces-before="0">Aqui estão alguns exemplos de mistura de aspas:</p>
```js
const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it.";
<pre><code class="js">const grouchoContraction = "I've had a perfectly wonderful evening, but this wasn't it.";
const quoteInString = "Groucho Marx once said 'Quote me as saying I was mis-quoted.'";
const uhOhGroucho = 'I've had a perfectly wonderful evening, but this wasn't it.';
```
`</pre>
The first two are correct, but the third is incorrect.
As duas primeiras estão corretas, mas a terceira não.
Of course, it is okay to use only one style of quotes. You can escape the quotes inside the string by using the backslash (`\`) escape character:
Claro, não há problema usar apenas um estilo de aspas. Você pode escapar as aspas dentro de uma string ao usar o caractere barra invertida (</code>\</code>):
```js
const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t it.';
@ -30,17 +29,17 @@ const allSameQuotes = 'I\'ve had a perfectly wonderful evening, but this wasn\'t
# --instructions--
Fix the string so it either uses different quotes for the `href` value, or escape the existing ones. Keep the double quote marks around the entire string.
Corrija a string para que ou use aspas diferentes para o valor de `href` ou escape as aspas existentes. Mantenha as aspas duplas ao redor de toda a string.
# --hints--
Your code should fix the quotes around the `href` value `#Home` by either changing or escaping them.
Seu código deve corrigir as aspas em torno do valor de `href`: `#Home` ao mudar ou escapar elas.
```js
assert(code.match(/<a href=\s*?('|\\")#Home\1\s*?>/g));
```
Your code should keep the double quotes around the entire string.
Seu código deve manter as aspas duplas ao redor de toda a string.
```js
assert(code.match(/"<p>.*?<\/p>";/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b86367417b2b2512b3b
title: Catch Off By One Errors When Using Indexing
title: Capture Erros de Fora Por Um Quando Usando Indexação
challengeType: 1
forumTopicId: 301189
dashedName: catch-off-by-one-errors-when-using-indexing
@ -8,9 +8,9 @@ dashedName: catch-off-by-one-errors-when-using-indexing
# --description--
<dfn>Off by one errors</dfn> (sometimes called OBOE) crop up when you're trying to target a specific index of a string or array (to slice or access a segment), or when looping over the indices of them. JavaScript indexing starts at zero, not one, which means the last index is always one less than the length of the item. If you try to access an index equal to the length, the program may throw an "index out of range" reference error or print `undefined`.
<dfn>Off by one errors (erros de fora por um)</dfn> (as vezes chamado OBOE) surge quando você está tentando acessar um índice específico de uma string ou array (para fatiar ou acessar um segmento), ou quando você está iterando sobre seus índices. A indexação de JavaScript começa em zero e não um, o que significa que o último índice sempre será o tamanho do item menos 1 (array.length - 1). Se você estiver tentando acessar um índice igual ao tamanho, o programa pode lançar uma referência do erro "index out of range" ou imprimir `undefined`.
When you use string or array methods that take index ranges as arguments, it helps to read the documentation and understand if they are inclusive (the item at the given index is part of what's returned) or not. Here are some examples of off by one errors:
Quando você usa métodos de string ou array que recebem intervalos de índices como argumentos, auxilia na leitura da documentação e compreender se eles são inclusivos (o item no índice especificado é parte do que é retornado) ou não. Aqui estão alguns exemplos de erros de fora por um:
```js
let alphabet = "abcdefghijklmnopqrstuvwxyz";
@ -26,33 +26,33 @@ for (let k = 0; k < len; k++) {
}
```
The first example here loops one too many times, and the second loops one too few times (missing the first index, 0). The third example is correct.
O primeiro exemplo itera uma vez a mais (i <= len) e o segundo itera uma vez a menos por começar do índice 1 (let j = 1). O terceiro exemplo está certo.
# --instructions--
Fix the two indexing errors in the following function so all the numbers 1 through 5 are printed to the console.
Corrija os dois erros de índices nas funções seguintes para que todos os números de 1 até 5 sejam exibidos no console.
# --hints--
Your code should set the initial condition of the loop so it starts at the first index.
Seu código deve definir a condição inicial do laço para começar do primeiro índice.
```js
assert(code.match(/i\s*?=\s*?0\s*?;/g).length == 1);
```
Your code should fix the initial condition of the loop so that the index starts at 0.
Seu código deve corrigir a condição inicial do laço para que o índice comece em 0.
```js
assert(!code.match(/i\s?=\s*?1\s*?;/g));
```
Your code should set the terminal condition of the loop so it stops at the last index.
Seu código deve definir a condição de parada do laço, a fim de parar no último índice.
```js
assert(code.match(/i\s*?<\s*?len\s*?;/g).length == 1);
```
Your code should fix the terminal condition of the loop so that it stops at 1 before the length.
Seu código deve corrigir a condição de parada do laço, a fim de parar no tamanho menos 1.
```js
assert(!code.match(/i\s*?<=\s*?len;/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b84367417b2b2512b36
title: 'Catch Unclosed Parentheses, Brackets, Braces and Quotes'
title: 'Identifique Parênteses, Colchetes, Chaves e Aspas Sem Fechamento'
challengeType: 1
forumTopicId: 301190
dashedName: catch-unclosed-parentheses-brackets-braces-and-quotes
@ -8,23 +8,23 @@ dashedName: catch-unclosed-parentheses-brackets-braces-and-quotes
# --description--
Another syntax error to be aware of is that all opening parentheses, brackets, curly braces, and quotes have a closing pair. Forgetting a piece tends to happen when you're editing existing code and inserting items with one of the pair types. Also, take care when nesting code blocks into others, such as adding a callback function as an argument to a method.
Outro erro de sintaxe para estar ciente é que todas as aberturas de parênteses, colchetes, chaves e aspas têm um par de fechamento. Esquecer um pedaço tende a acontecer quando você está editando um código existente e inserindo itens com um dos tipos de pares. Também, tenha cuidado ao aninhar blocos de código em outros, como adicionar uma função de callback como um argumento a um método.
One way to avoid this mistake is as soon as the opening character is typed, immediately include the closing match, then move the cursor back between them and continue coding. Fortunately, most modern code editors generate the second half of the pair automatically.
Uma maneira de evitar esse erro é assim que o caractere de abertura é digitado, imediatamente inclua o caractere de fechamento, mova o cursor entre eles e continue programando. Felizmente, a maioria dos editores de código modernos geram a segunda parte do par automaticamente.
# --instructions--
Fix the two pair errors in the code.
Corrija os dois erros de pares no código.
# --hints--
Your code should fix the missing piece of the array.
Seu código deve corrigir o pedaço que falta do array.
```js
assert(code.match(/myArray\s*?=\s*?\[\s*?1\s*?,\s*?2\s*?,\s*?3\s*?\];/g));
```
Your code should fix the missing piece of the `.reduce()` method. The console output should show that `Sum of array values is: 6`.
Seu código deve corrigir o pedaço que falta do método `.reduce()`. A saída no console deve mostrar que `Sum of array value is: 6`.
```js
assert(arraySum === 6);

View File

@ -1,6 +1,6 @@
---
id: 587d7b85367417b2b2512b38
title: Catch Use of Assignment Operator Instead of Equality Operator
title: Identifique Uso do Operador de Atribuição ao invés do Operador de Igualdade
challengeType: 1
forumTopicId: 301191
dashedName: catch-use-of-assignment-operator-instead-of-equality-operator
@ -8,13 +8,13 @@ dashedName: catch-use-of-assignment-operator-instead-of-equality-operator
# --description--
Branching programs, i.e. ones that do different things if certain conditions are met, rely on `if`, `else if`, and `else` statements in JavaScript. The condition sometimes takes the form of testing whether a result is equal to a value.
Programas de ramificação, ou seja, programas que fazem coisas diferentes se certas condições forem atendidas, dependem de instruções `i`, `else if` e `else` em JavaScript. Às vezes a condição verifica se um resultado é igual a um valor.
This logic is spoken (in English, at least) as "if x equals y, then ..." which can literally translate into code using the `=`, or assignment operator. This leads to unexpected control flow in your program.
Essa lógica é fala da seguinte forma: "se x for igual a y, então ..." o que pode literalmente ser traduzido para código usando o `=`, ou operador de atribuição. Isso leva a um controle de fluxo inesperado no seu programa.
As covered in previous challenges, the assignment operator (`=`) in JavaScript assigns a value to a variable name. And the `==` and `===` operators check for equality (the triple `===` tests for strict equality, meaning both value and type are the same).
Como abordado nos desafios anteriores, o operador de atribuição (`=`) em JavaScript, atribui um valor para o nome de uma variável. E os operadores `==` e `===` verificam pela igualdade (o triplo `===` testa por igualdade estrita, significando que ambos os valores e o tipo de dado são os mesmos).
The code below assigns `x` to be 2, which evaluates as `true`. Almost every value on its own in JavaScript evaluates to `true`, except what are known as the "falsy" values: `false`, `0`, `""` (an empty string), `NaN`, `undefined`, and `null`.
O código abaixo atribui `x` para ser 2, o que tem como resultado `true`. Quase todo valor por si só em JavaScript são avaliados como `true`, exceto com o que são conhecidos como valores falsos: `false`, `0`, `""` (uma string vazia), `NaN`, `undefined` e `null`.
```js
let x = 1;
@ -26,21 +26,21 @@ if (x = y) {
}
```
In this example, the code block within the `if` statement will run for any value of `y`, unless `y` is falsy. The `else` block, which we expect to run here, will not actually run.
Nesse exemplo, o bloco de código dentro da instrução `if` irá rodar para qualquer valor de `y`, a não ser que `y` seja falso. O bloco de `else`, que nós esperamos ser executado aqui, não irá realmente rodar.
# --instructions--
Fix the condition so the program runs the right branch, and the appropriate value is assigned to `result`.
Corrija a condição para que o programa rode na ramificação correta e o valor apropriado seja atribuído a `result`.
# --hints--
Your code should fix the condition so it checks for equality, instead of using assignment.
Seu código deve corrigir a condição para que verifique pela igualdade, ao invés de usar atribuição.
```js
assert(result == 'Not equal!');
```
The condition should use either `==` or `===` to test for equality.
A condição deve usar `==` ou `===` para verificar a igualdade.
```js
assert(code.match(/x\s*?===?\s*?y/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b86367417b2b2512b3d
title: Prevent Infinite Loops with a Valid Terminal Condition
title: Previna Laços Infinitos com uma Condição de Término Válida
challengeType: 1
forumTopicId: 301192
dashedName: prevent-infinite-loops-with-a-valid-terminal-condition
@ -8,9 +8,9 @@ dashedName: prevent-infinite-loops-with-a-valid-terminal-condition
# --description--
The final topic is the dreaded infinite loop. Loops are great tools when you need your program to run a code block a certain number of times or until a condition is met, but they need a terminal condition that ends the looping. Infinite loops are likely to freeze or crash the browser, and cause general program execution mayhem, which no one wants.
O tópico final é o temido laço infinito. Laços são ótimas ferramentas quando você precisa que o seu programa rode um bloco de código uma quantidade exata de vezes ou até que uma condição seja atendida, mas eles precisam de uma condição de parada que finalize esse laço. Laços infinitos têm alta probabilidade de congelar ou travar o navegador, e causa um caos na execução geral do programa, o que ninguém deseja.
There was an example of an infinite loop in the introduction to this section - it had no terminal condition to break out of the `while` loop inside `loopy()`. Do NOT call this function!
Havia um exemplo de laço infinito na introdução dessa seção - esse laço não tinha uma condição de parada para sair do laço `while` dentro de `loopy()`. NÃO chame essa função!
```js
function loopy() {
@ -20,21 +20,21 @@ function loopy() {
}
```
It's the programmer's job to ensure that the terminal condition, which tells the program when to break out of the loop code, is eventually reached. One error is incrementing or decrementing a counter variable in the wrong direction from the terminal condition. Another one is accidentally resetting a counter or index variable within the loop code, instead of incrementing or decrementing it.
É trabalho do programador garantir que a condição de parada, a qual avisa ao programa quando sair de um laço, é eventualmente alcançada. Um erro é incrementar ou decrementar uma variável contadora na direção errada da condição de parada. Outro erro é acidentalmente reiniciar uma variável contadora ou de índice dentro do laço, ao invés de incrementar ou decrementar.
# --instructions--
The `myFunc()` function contains an infinite loop because the terminal condition `i != 4` will never evaluate to `false` (and break the looping) - `i` will increment by 2 each pass, and jump right over 4 since `i` is odd to start. Fix the comparison operator in the terminal condition so the loop only runs for `i` less than or equal to 4.
A função `myFunc()` contém um laço infinito porque a condição de parada `i != 4` nunca será `false` (e então quebrar o laço) - `i` irá incrementar em 2 a cada iteração, e passa direto por 4 já que `i` é ímpar no início. Corrija o operador de comparação para que o laço só rode enquanto `i` for menor ou igual a 4.
# --hints--
Your code should change the comparison operator in the terminal condition (the middle part) of the `for` loop.
Seu código deve alterar o operador de comparação na condição de parada (parte do meio) do laço `for`.
```js
assert(code.match(/i\s*?<=\s*?4;/g).length == 1);
```
Your code should fix the comparison operator in the terminal condition of the loop.
Seu código deve corrigir o operador de comparação na condição de parada do laço.
```js
assert(!code.match(/i\s*?!=\s*?4;/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b83367417b2b2512b37
title: Understanding the Differences between the freeCodeCamp and Browser Console
title: Entendendo a Diferença entre o console da freeCodeCamp e do Navegador
challengeType: 1
forumTopicId: 301193
dashedName: understanding-the-differences-between-the-freecodecamp-and-browser-console
@ -8,27 +8,27 @@ dashedName: understanding-the-differences-between-the-freecodecamp-and-browser-c
# --description--
You may have noticed that some freeCodeCamp JavaScript challenges include their own console. This console behaves a little differently than the browser console you used in the last challenge.
Você pode ter percebido que alguns dos desafios de JavaScript da freeCodeCamp incluem seu próprio console. Esse console se comporta um pouco difrente do console do navegador que você utilizou no último desafio.
The following challenge is meant to highlight the main difference between the freeCodeCamp console and your browser console.
O desafio a seguir tem a finalidade de destacar a principal diferença entre o console da freeCodeCamp e do navegador.
When you run ordinary JavaScript, the browser's console will display your `console.log()` statements the exact number of times it is called.
Quando você executa JavaScript comum, o console do navegado exibirá suas instruções `console.log()` a exata quantidade de vezes que é chamada.
The freeCodeCamp console will print your `console.log()` statements a short time after the editor detects a change in the script, as well as during testing.
O console da freeCodeCamp irá imprimir suas instruções `console.log()` um curto período depois do editor detectar mudança no script, e também durante o teste.
The freeCodeCamp console is cleared before the tests are run and, to avoid spam, only prints the logs during the first test (see the note below for exceptions).
O console da freeCodeCamp é apagado antes de cada execução de testes e, para evitar spam, só imprime os logs durante o primeiro teste (veja a nota abaixo para exceções).
If you would like to see every log for every test, run the tests, and open the browser console. If you prefer to use the browser console, and want it to mimic the freeCodeCamp console, place `console.clear()` before any other `console` calls, to clear the browser console.
Se você gostaria de ver todos os logs em todos os testes, execute os testes e abra o console do navegador. Se preferir usar o console do navegador e quiser que ele imite o console da freeCodeCamp, coloque `console.clear()` antes de qualquer outra chamada ao `console`, para apagar o console do navegador.
**Note:** `console.log`s inside functions are printed to the freeCodeCamp console whenever those functions are called. This can help debugging functions that are called during testing.
**Nota:** `console.log` dentro de funções são impressas no console da freeCodeCamp toda vez que essas funções forem chamadas. Isso pode ajudar a depurar (ou debugar) funções que são chamadas durante os testes.
# --instructions--
First, use `console.log` to log the `output` variable. Then, use `console.clear` to clear the browser console.
Primeiro, use `console.log` para exibir a variável `output`. Em seguida, use `console.clear` para apagar o console do navegador.
# --hints--
You should use `console.clear()` to clear the browser console.
Você deve usar `console.clear()` para apagar o console do navegador.
```js
assert(
@ -38,7 +38,7 @@ assert(
);
```
You should use `console.log()` to print the `output` variable.
Você deve usar `console.log()` para imprimir a variável `output`.
```js
assert(__helpers.removeWhiteSpace(code).match(/console\.log\(output\)/));

View File

@ -1,6 +1,6 @@
---
id: 587d7b86367417b2b2512b3c
title: Use Caution When Reinitializing Variables Inside a Loop
title: Tenha Cuidado Quando Reinicializando Variáveis Dentro de Laços
challengeType: 1
forumTopicId: 301194
dashedName: use-caution-when-reinitializing-variables-inside-a-loop
@ -8,29 +8,29 @@ dashedName: use-caution-when-reinitializing-variables-inside-a-loop
# --description--
Sometimes it's necessary to save information, increment counters, or re-set variables within a loop. A potential issue is when variables either should be reinitialized, and aren't, or vice versa. This is particularly dangerous if you accidentally reset the variable being used for the terminal condition, causing an infinite loop.
Às vezes é necessário salvar informações, incrementar contadores ou redefinir variáveis dentro de um laço. Um potencial problema é quando variáveis deveriam ser reinicializadas e, não são, ou vice versa. Isso é particularmente perigoso se você acidentalmente redefinir a variável sendo usada para a a condição de parada, causando um laço infinito.
Printing variable values with each cycle of your loop by using `console.log()` can uncover buggy behavior related to resetting, or failing to reset a variable.
Imprimir os valores das variáveis em cada ciclo do seu laço usando `console.log()` pode descobrir comportamentos com bugs relacionados a reiniciar ou falhar ao reiniciar uma variável.
# --instructions--
The following function is supposed to create a two-dimensional array with `m` rows and `n` columns of zeroes. Unfortunately, it's not producing the expected output because the `row` variable isn't being reinitialized (set back to an empty array) in the outer loop. Fix the code so it returns a correct 3x2 array of zeroes, which looks like `[[0, 0], [0, 0], [0, 0]]`.
A seguinte função deveria criar um array de duas dimensões com `m` linhas e `n` colunas de zeros. Infelizmente, não está produzindo a saída esperada porque a variável `row` não está sendo reiniciada (definida de volta para um array vazio) no laço mais externo. Corrija o código para que retorne o array de zeros correto (dimensão: 3x2), que se parece com `[[0, 0], [0, 0], [0, 0]]`.
# --hints--
Your code should set the `matrix` variable to an array holding 3 rows of 2 columns of zeroes each.
Seu código deve definir a variável `matrix` para um array contendo 3 linhas de 2 colunas de zeros.
```js
assert(JSON.stringify(matrix) == '[[0,0],[0,0],[0,0]]');
```
The `matrix` variable should have 3 rows.
A variável `matrix` deve ter 3 linhas.
```js
assert(matrix.length == 3);
```
The `matrix` variable should have 2 columns in each row.
A variável `matrix` deve ter 2 colunas em cada linha.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b83367417b2b2512b33
title: Use the JavaScript Console to Check the Value of a Variable
title: Use o Console JavaScript para Verificar o Valor de uma Variável
challengeType: 1
forumTopicId: 18372
dashedName: use-the-javascript-console-to-check-the-value-of-a-variable
@ -8,13 +8,13 @@ dashedName: use-the-javascript-console-to-check-the-value-of-a-variable
# --description--
Both Chrome and Firefox have excellent JavaScript consoles, also known as DevTools, for debugging your JavaScript.
Ambos o Chrome e o Firefox possui excelentes consoles JavaScript, também conhecidos como DevTools, para depurar seu JavaScript.
You can find Developer tools in your Chrome's menu or Web Console in Firefox's menu. If you're using a different browser, or a mobile phone, we strongly recommend switching to desktop Firefox or Chrome.
Você pode encontrar Developer tools no menu do seu Chrome ou Web Console no menu do Firefox. Se você estiver usando um navegador diferente, ou um telefone móvel, recomendamos fortemente mudar para o Firefox ou Chrome Desktop.
The `console.log()` method, which "prints" the output of what's within its parentheses to the console, will likely be the most helpful debugging tool. Placing it at strategic points in your code can show you the intermediate values of variables. It's good practice to have an idea of what the output should be before looking at what it is. Having check points to see the status of your calculations throughout your code will help narrow down where the problem is.
O método `console.log()`, o qual "imprime" a saída do que está nos seus parênteses no console, irá provavelmente ser a ferramenta de debug mais útil. Colocá-lo em pontos estratégicos no seu código pode te mostrar os valores intermediários de variáveis. É uma boa prática ter uma ideia do que deveria ser a saída antes de olhar o que é. Ter pontos de verificação para ver o status de seus cálculos ao longo do seu código ajudará a encontrar onde o problema está.
Here's an example to print the string `Hello world!` to the console:
Aqui está um exemplo para imprimir a string `Hello world!` no console:
```js
console.log('Hello world!');
@ -22,11 +22,11 @@ console.log('Hello world!');
# --instructions--
Use the `console.log()` method to print the value of the variable `a` where noted in the code.
Use o método `console.log()` para imprimir o valor da variável `a` aonde anotou no código.
# --hints--
Your code should use `console.log()` to check the value of the variable `a`.
Seu código deve usar `console.log()` para verificar o valor da variável `a`.
```js
assert(code.match(/console\.log\(a\)/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b84367417b2b2512b34
title: Use typeof to Check the Type of a Variable
title: Use typeof para Verificar o Tipo da Variável
challengeType: 1
forumTopicId: 18374
dashedName: use-typeof-to-check-the-type-of-a-variable
@ -8,9 +8,9 @@ dashedName: use-typeof-to-check-the-type-of-a-variable
# --description--
You can use `typeof` to check the data structure, or type, of a variable. This is useful in debugging when working with multiple data types. If you think you're adding two numbers, but one is actually a string, the results can be unexpected. Type errors can lurk in calculations or function calls. Be careful especially when you're accessing and working with external data in the form of a JavaScript Object Notation (JSON) object.
Você pode usar `typeof` para verificar a estrutura de dado, ou tipo, de uma variável. Isso é útil na depuração quando trabalhando com diversos tipos de dados. Se você pensar que está adicionando dois números, mas na verdade um é na verdade uma string, o resultado pode ser inesperado. Erros de tipo podem se esconder em cálculos ou chamada de funções. Seja cuidadoso especialmente quando você estiver acessando e trabalhando com dados externos na forma de um objeto JavaScript Object Notation (JSON).
Here are some examples using `typeof`:
Aqui está alguns exemplos usando `typeof`:
```js
console.log(typeof "");
@ -19,29 +19,29 @@ console.log(typeof []);
console.log(typeof {});
```
In order, the console will display the strings `string`, `number`, `object`, and `object`.
Em ordem, o console exibirá as strings `string`, `number`, `object` e `object`.
JavaScript recognizes six primitive (immutable) data types: `Boolean`, `Null`, `Undefined`, `Number`, `String`, and `Symbol` (new with ES6) and one type for mutable items: `Object`. Note that in JavaScript, arrays are technically a type of object.
JavaScript reconhece seis tipos de dados primitivos (imutável): `Boolean`, `Null`, `Undefined`, `Number`, `String` e `Symbol` (novo em ES6) e um tipo para itens mutáveis: `Object`. Note que em JavaScript, arrays são tecnicamente um tipo de objeto.
# --instructions--
Add two `console.log()` statements to check the `typeof` each of the two variables `seven` and `three` in the code.
Adicione duas instruções `console.log()` para verificar o `typeof` de cada uma das duas variáveis `seven` e `three` no código.
# --hints--
Your code should use `typeof` in two `console.log()` statements to check the type of the variables.
Seu código deve usar `typeof` em duas instruções `console.log()` para verificar o tipo das variáveis.
```js
assert(code.match(/console\.log\(typeof[\( ].*\)?\)/g).length == 2);
```
Your code should use `typeof` to check the type of the variable `seven`.
Seu código deve usar `typeof` para verificar o tipo da variável `seven`.
```js
assert(code.match(/typeof[\( ]seven\)?/g));
```
Your code should use `typeof` to check the type of the variable `three`.
Seu código deve usar `typeof` para verificar o tipo da variável `three`.
```js
assert(code.match(/typeof[\( ]three\)?/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7b87367417b2b2512b40
title: Compare Scopes of the var and let Keywords
title: Compare Escopos das Palavras-Chaves var e let
challengeType: 1
forumTopicId: 301195
dashedName: compare-scopes-of-the-var-and-let-keywords
@ -8,11 +8,11 @@ dashedName: compare-scopes-of-the-var-and-let-keywords
# --description--
When you declare a variable with the `var` keyword, it is declared globally, or locally if declared inside a function.
Quando você declara uma variável com a palavra-chave `var`, ela é declarada globalmente, ou localmente se declarada dentro de uma função.
The `let` keyword behaves similarly, but with some extra features. When you declare a variable with the `let` keyword inside a block, statement, or expression, its scope is limited to that block, statement, or expression.
A palvara-chave `let` se comporta de forma similar, mas com alguns recursos extras. Quando você declara a variável com a palavra-chave `let` dentro de um bloco, declaração, ou expressão, seu escopo é limitado ao bloco, declaração, ou expressão.
For example:
Por exemplo:
```js
var numArray = [];
@ -23,9 +23,9 @@ console.log(numArray);
console.log(i);
```
Here the console will display the values `[0, 1, 2]` and `3`.
Aqui o console irá exibir os valores `[0, 1, 2]` e `3`.
With the `var` keyword, `i` is declared globally. So when `i++` is executed, it updates the global variable. This code is similar to the following:
Com a palavra-chave `var`, `i` é declarado globalmente. Então quando `i++` é executado, ele atualiza a variável global. Esse código é semelhante ao seguinte:
```js
var numArray = [];
@ -37,9 +37,9 @@ console.log(numArray);
console.log(i);
```
Here the console will display the values `[0, 1, 2]` and `3`.
Aqui o console irá exibir os valores `[0, 1, 2]` e `3`.
This behavior will cause problems if you were to create a function and store it for later use inside a `for` loop that uses the `i` variable. This is because the stored function will always refer to the value of the updated global `i` variable.
Este comportamento causará problemas se você criasse uma função e armazená-la para depois utilizar dentro de um laço `for` que utiliza a variável `i`. Isso se deve ao fato da função armazenada sempre irá se referir ao valor da variável global `i` atualizada.
```js
var printNumTwo;
@ -53,9 +53,9 @@ for (var i = 0; i < 3; i++) {
console.log(printNumTwo());
```
Here the console will display the value `3`.
Aqui o console irá exibir o valor `3`.
As you can see, `printNumTwo()` prints 3 and not 2. This is because the value assigned to `i` was updated and the `printNumTwo()` returns the global `i` and not the value `i` had when the function was created in the for loop. The `let` keyword does not follow this behavior:
Como você pode ver, `printNumTwo()` exibe 3 e não 2. Isso se deve ao fato do valor atribuído a `i` foi atualizado e `printNumTwo()` retorna a variável global `i` e não o valor que `i` tinha quando a função foi criada dentro do laço for. A palavra-chave `let` não segue este comportamento:
```js
let printNumTwo;
@ -70,25 +70,25 @@ console.log(printNumTwo());
console.log(i);
```
Here the console will display the value `2`, and an error that `i is not defined`.
Aqui o console irá exibir o valor `2`, e um erro que `i is not defined (i não foi definido)`.
`i` is not defined because it was not declared in the global scope. It is only declared within the `for` loop statement. `printNumTwo()` returned the correct value because three different `i` variables with unique values (0, 1, and 2) were created by the `let` keyword within the loop statement.
`i` não foi definido porque não foi declarado no escopo global. É declarado apenas dentro da declaração do laço `for`. `printNumTwo()` retornou o valor correto porque três variáveis `i` distintas com valores únicos (0, 1 e 2) foram criados com a palavra-chave `let` dentro da declaração do laço.
# --instructions--
Fix the code so that `i` declared in the `if` statement is a separate variable than `i` declared in the first line of the function. Be certain not to use the `var` keyword anywhere in your code.
Corrija o código para que `i` declarado dentro do comando `if` seja uma variável diferente de `i` declarada na primeira linha da função. Tenha certeza de não usar a palavra-chave `var` em nenhum lugar do seu código.
This exercise is designed to illustrate the difference between how `var` and `let` keywords assign scope to the declared variable. When programming a function similar to the one used in this exercise, it is often better to use different variable names to avoid confusion.
Este exercício foi projetado para ilustrar a diferença ente como as palavras-chaves `var` e `let` definem o escopo para a variável declarada. Quando programamos uma função semelhar a aquelas utilizadas no exercício, geralmente é melhor utilizar variáveis distintas para evitar confusão.
# --hints--
`var` should not exist in code.
`var` não deve existir no código.
```js
(getUserInput) => assert(!getUserInput('index').match(/var/g));
```
The variable `i` declared in the `if` statement should equal the string `block scope`.
A variável `i` declarada dentro do corpo do comando `if` deve ser igual a string `block scope`.
```js
(getUserInput) =>
@ -97,7 +97,7 @@ The variable `i` declared in the `if` statement should equal the string `block s
);
```
`checkScope()` should return the string `function scope`
`checkScope()` deve retornar a string `function scope`
```js
assert(checkScope() === 'function scope');

View File

@ -1,6 +1,6 @@
---
id: 5cdafbc32913098997531680
title: Complete a Promise with resolve and reject
title: Concluir uma Promessa com resolve e reject
challengeType: 1
forumTopicId: 301196
dashedName: complete-a-promise-with-resolve-and-reject
@ -8,7 +8,7 @@ dashedName: complete-a-promise-with-resolve-and-reject
# --description--
A promise has three states: `pending`, `fulfilled`, and `rejected`. The promise you created in the last challenge is forever stuck in the `pending` state because you did not add a way to complete the promise. The `resolve` and `reject` parameters given to the promise argument are used to do this. `resolve` is used when you want your promise to succeed, and `reject` is used when you want it to fail. These are methods that take an argument, as seen below.
Uma promessa possui três estados: pendente (`pending`), cumprida (`fulfilled`) e rejeitada (`rejected`). A promessa que você criou no desafio anterior está presa no estado `pending` para sempre porque você não adicionou uma forma de concluir a promessa. Os parâmetros `resolve` e `reject` passados para o argumento da promessa servem para este propósito. `resolve` é utilizado quando a promessa for bem sucedida, enquanto que `reject` é utilizado quando ela falhar. Ambos são métodos que recebem apenas um argumento, como no exemplo abaixo.
```js
const myPromise = new Promise((resolve, reject) => {
@ -20,15 +20,15 @@ const myPromise = new Promise((resolve, reject) => {
});
```
The example above uses strings for the argument of these functions, but it can really be anything. Often, it might be an object, that you would use data from, to put on your website or elsewhere.
O exemplo acima usa strings como argumento desses métodos, mas você pode passar qualquer outro tipo de dado. Geralmente, é passado um objeto para esses métodos. Assim você pode acessar as propriedades deste objeto e usá-los em seu site ou em qualquer outro lugar.
# --instructions--
Make the promise handle success and failure. If `responseFromServer` is `true`, call the `resolve` method to successfully complete the promise. Pass `resolve` a string with the value `We got the data`. If `responseFromServer` is `false`, use the `reject` method instead and pass it the string: `Data not received`.
Adapte a promessa para ambas as situações de sucesso e fracasso. Se `responseFromServer` for `true`, chame o método `resolve` para completar a promessa com sucesso. Passe a string `We got the data` como argumento para o método `resolve`. Se `responseFromServer` for `false`, passe a string `Data not received` como argumento para o método `reject`.
# --hints--
`resolve` should be called with the expected string when the `if` condition is `true`.
O método `resolve` deve ser chamado com a string informada anteriormente quando a condição do `if` for `true`.
```js
assert(
@ -36,7 +36,7 @@ assert(
);
```
`reject` should be called with the expected string when the `if` condition is `false`.
O método `reject` deve ser chamado com a string informada anteriormente quando a condição do `if` for `false`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5cdafbb0291309899753167f
title: Create a JavaScript Promise
title: Criar uma Promessa em JavaScript
challengeType: 1
forumTopicId: 301197
dashedName: create-a-javascript-promise
@ -8,7 +8,7 @@ dashedName: create-a-javascript-promise
# --description--
A promise in JavaScript is exactly what it sounds like - you use it to make a promise to do something, usually asynchronously. When the task completes, you either fulfill your promise or fail to do so. `Promise` is a constructor function, so you need to use the `new` keyword to create one. It takes a function, as its argument, with two parameters - `resolve` and `reject`. These are methods used to determine the outcome of the promise. The syntax looks like this:
Uma promessa em JavaScript é exatamente o que parece - você faz a promessa de que irá fazer uma tarefa, geralmente de forma asncrona. Quando a tarefa é finalizada, ou você cumpriu a promessa ou falhou ao tentar. Por ser uma função construtora, você precisa utilizar a palavra-chave `new` para criar uma `Promise`. Ele recebe uma função, como seu arguemento, com dois parâmetros - `resolve` e `reject`. Esses métodos são usados para determinar o resultado da promessa. A sintaxe se parecesse com isso:
```js
const myPromise = new Promise((resolve, reject) => {
@ -18,17 +18,17 @@ const myPromise = new Promise((resolve, reject) => {
# --instructions--
Create a new promise called `makeServerRequest`. Pass in a function with `resolve` and `reject` parameters to the constructor.
Crie uma nova promessa chamada `makeServerRequest`. No construtor da promessa, passe uma função com os parâmetros `resolve` e `reject`.
# --hints--
You should assign a promise to a declared variable named `makeServerRequest`.
Você deve atribuir a promessa a uma variável chamada `makeServerRequest`.
```js
assert(makeServerRequest instanceof Promise);
```
Your promise should receive a function with `resolve` and `reject` as parameters.
A promessa deve receber uma função com os parâmetros `resolve` e `reject`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5cddbfd622f1a59093ec611d
title: Create a Module Script
title: Separar seus scripts em módulos
challengeType: 6
forumTopicId: 301198
dashedName: create-a-module-script
@ -8,27 +8,27 @@ dashedName: create-a-module-script
# --description--
JavaScript started with a small role to play on an otherwise mostly HTML web. Today, its huge, and some websites are built almost entirely with JavaScript. In order to make JavaScript more modular, clean, and maintainable; ES6 introduced a way to easily share code among JavaScript files. This involves exporting parts of a file for use in one or more other files, and importing the parts you need, where you need them. In order to take advantage of this functionality, you need to create a script in your HTML document with a `type` of `module`. Heres an example:
O JavaScript nasceu com com o objetivo de cumprir um pequeno papel em uma web onde tudo era, na maior parte, HTML. Hoje, o JavaScript é gigante. Para se ter noção, alguns websites são construídos quase que inteiramente em JavaScript. A fim de tornar o JavaScript mais modular, limpo e passível de manutenção, a versão ES6 introduziu uma forma mais simples de compartilhar códigos entre arquivos JavaScript. Dessa forma, você consegue exportar partes de um arquivo e usá-los em arquivos externos bem como importar as partes que você precisa. Para tirar proveito dessa funcionalidade, você precisa crair uma tag script com o atributo `type` de valor `module` no seu documento HTML. Aqui está um exemplo:
```html
<script type="module" src="filename.js"></script>
```
A script that uses this `module` type can now use the `import` and `export` features you will learn about in the upcoming challenges.
O script do exemplo acima agora é um módulo (`module`) e pode usar os recursos `import` e `export` (você aprenderá sobre eles nos próximos desafios).
# --instructions--
Add a script to the HTML document of type `module` and give it the source file of `index.js`
Adicione uma tag script ao documento HTML do tipo `module` e dê a ela o caminho do arquivo `index.js`
# --hints--
You should create a `script` tag.
Você deve criar uma tag `script`.
```js
assert(code.match(/<\s*script[^>]*>\s*<\/\s*script\s*>/g));
```
Your `script` tag should have the `type` attribute with a value of `module`.
A tag `script` deve ter o atributo `type` com o valor `module`.
```js
assert(
@ -38,7 +38,7 @@ assert(
);
```
Your `script` tag should have a `src` of `index.js`.
A tag `script` deve ter o atributo `src` com o valor `index.js`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b8c367417b2b2512b58
title: Create an Export Fallback with export default
title: Exportar apenas um valor com export default
challengeType: 1
forumTopicId: 301199
dashedName: create-an-export-fallback-with-export-default
@ -8,11 +8,11 @@ dashedName: create-an-export-fallback-with-export-default
# --description--
In the `export` lesson, you learned about the syntax referred to as a <dfn>named export</dfn>. This allowed you to make multiple functions and variables available for use in other files.
Na lição de `export` você aprendeu sobre a sintaxe que chamamos de <dfn>exportação nomeada</dfn>. Naquela lição você exportou múltiplas funções e variáveis que ficaram disponíveis para utilização em outros arquivos.
There is another `export` syntax you need to know, known as <dfn>export default</dfn>. Usually you will use this syntax if only one value is being exported from a file. It is also used to create a fallback value for a file or module.
Há outra sintaxe para `export` que você precisa saber, conhecida como <dfn>exportação padrão</dfn>. Você usará essa sintaxe quando apenas um valor estiver sendo exportado de um arquivo ou módulo. Essa sintaxe também é usada para exportar um valor substituto caso o valor original não possa ser exportado.
Below are examples using `export default`:
Abaixo estão exemplos utilizando a sintaxe `export default`:
```js
export default function add(x, y) {
@ -24,17 +24,17 @@ export default function(x, y) {
}
```
The first is a named function, and the second is an anonymous function.
O primeiro exemplo é uma função nomeada e o segundo é uma função anônima.
Since `export default` is used to declare a fallback value for a module or file, you can only have one value be a default export in each module or file. Additionally, you cannot use `export default` with `var`, `let`, or `const`
A sintaxe `export default` é usada para exportar um único valor de um arquivo ou módulo. Tenha em mente que você não pode usar o `export default` com `var`, `let` ou `const`
# --instructions--
The following function should be the fallback value for the module. Please add the necessary code to do so.
A função a seguir deve ser o único valor a ser exportado. Adicione o código necessário para que apenas um valor seja exportado.
# --hints--
Your code should use an `export` fallback.
Você deve usar a sintaxe alternativa ao `export`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7b8a367417b2b2512b4e
title: Create Strings using Template Literals
title: Criar Strings usando Template Literals
challengeType: 1
forumTopicId: 301200
dashedName: create-strings-using-template-literals
@ -8,11 +8,11 @@ dashedName: create-strings-using-template-literals
# --description--
A new feature of ES6 is the <dfn>template literal</dfn>. This is a special type of string that makes creating complex strings easier.
Um novo recurso introduzido na versão ES6 é o <dfn>template literal</dfn>. Esse é um tipo especial de string que torna mais fácil a criação de strings complexas.
Template literals allow you to create multi-line strings and to use string interpolation features to create strings.
Template literals nos permite criar strings de mais de uma linha e usar os recursos de interpolação de strings.
Consider the code below:
Considere o código abaixo:
```js
const person = {
@ -26,15 +26,15 @@ I am ${person.age} years old.`;
console.log(greeting);
```
The console will display the strings `Hello, my name is Zodiac Hasbro!` and `I am 56 years old.`.
O console irá exibir as strings `Hello, my name is Zodiac Hasbro!` e `I am 56 years old.`.
A lot of things happened there. Firstly, the example uses backticks (`` ` ``), not quotes (`'` or `"`), to wrap the string. Secondly, notice that the string is multi-line, both in the code and the output. This saves inserting `\n` within strings. The `${variable}` syntax used above is a placeholder. Basically, you won't have to use concatenation with the `+` operator anymore. To add variables to strings, you just drop the variable in a template string and wrap it with `${` and `}`. Similarly, you can include other expressions in your string literal, for example `${a + b}`. This new way of creating strings gives you more flexibility to create robust strings.
Muitas coisas aconteceram aqui. Primeiro, o exemplo utiliza crases, ou backticks em Inglês, (`` ` ``), ao invés de aspas (`'` ou `"`), ao redor da string. Segundo, note que a string tem mais de uma linha, tanto no código quanto na saída. Isso torna desnecessário inserir `\n` dentro das strings. A sintaxe `${variable}` usada acima é um espaço reservado (placeholder). Basicamente, você não terá mais que usar concatenação com o operador `+`. Para adicionar o valor de uma variável à string, você a envolve com `${` e `}`. Além de poder usar variáveis, você pode incluir outras expressões. Como por exemplo `${a + b}`. Essa nova maneira de criar strings te dá mais flexibilidade na hora de criar string complexas.
# --instructions--
Use template literal syntax with backticks to create an array of list element (`li`) strings. Each list element's text should be one of the array elements from the `failure` property on the `result` object and have a `class` attribute with the value `text-warning`. The `makeList` function should return the array of list item strings.
Use a sintaxe de template literal com crases para criar um array de strings de elementos de lista (`li`). Analise a propriedade `failure` do objeto `result`. O texto de cada elemento li deve ser um dos elementos contidos no array dentro da propriedade failure e cada li deve ter o atributo `class` com o valor `text-warning`. A função `makeList` deve retornar um array de strings de elementos li.
Use an iterator method (any kind of loop) to get the desired output (shown below).
Abaixo está um exemplo do array que você deve criar. Use um loop para criar o mesmo resultado.
```js
[
@ -46,7 +46,7 @@ Use an iterator method (any kind of loop) to get the desired output (shown below
# --hints--
`failuresList` should be an array containing `result failure` messages.
A variável `failuresList` deve ser um array contendo as mensagens de `result failure`.
```js
assert(
@ -54,7 +54,7 @@ assert(
);
```
`failuresList` should be equal to the specified output.
A variável `failuresList` deve ser igual ao array mostrado anteriormente.
```js
assert(
@ -66,13 +66,13 @@ assert(
);
```
Template strings and expression interpolation should be used.
Template strings e interpolação de expressões - ${} - devem ser usados.
```js
(getUserInput) => assert(getUserInput('index').match(/(`.*\${.*}.*`)/));
```
An iterator should be used.
Você deve usar um loop.
```js
(getUserInput) =>

Some files were not shown because too many files have changed in this diff Show More