chore(i8n,curriculum): processed translations (#41521)
Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
This commit is contained in:
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b89367417b2b2512b4b
|
||||
title: Use Destructuring Assignment to Assign Variables from Arrays
|
||||
title: Usa sintaxis de desestructuración para asignar variables desde arreglos
|
||||
challengeType: 1
|
||||
forumTopicId: 301213
|
||||
dashedName: use-destructuring-assignment-to-assign-variables-from-arrays
|
||||
@ -8,43 +8,47 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
ES6 makes destructuring arrays as easy as destructuring objects.
|
||||
ES6 hace que desestructurar arreglos sea tan fácil como desestructurar objetos.
|
||||
|
||||
One key difference between the spread operator and array destructuring is that the spread operator unpacks all contents of an array into a comma-separated list. Consequently, you cannot pick or choose which elements you want to assign to variables.
|
||||
Una diferencia clave entre el operador de propagación y la desestructuración de arreglos es que el operador de propagación desempaca todos los contenidos de un arreglo en una lista separada por comas. En consecuencia, no puedes elegir qué elementos deseas asignar como variables.
|
||||
|
||||
Destructuring an array lets us do exactly that:
|
||||
Desestructurar un arreglo nos permite hacer exactamente eso:
|
||||
|
||||
```js
|
||||
const [a, b] = [1, 2, 3, 4, 5, 6];
|
||||
console.log(a, b); // 1, 2
|
||||
console.log(a, b);
|
||||
```
|
||||
|
||||
The variable `a` is assigned the first value of the array, and `b` is assigned the second value of the array. We can also access the value at any index in an array with destructuring by using commas to reach the desired index:
|
||||
La consola mostrará los valores de `a` y `b` como `1, 2`.
|
||||
|
||||
A la variable `a` se le asigna el primer valor del arreglo, y a `b` se le asigna el segundo valor del arreglo. También podemos acceder al valor en cualquier índice de un arreglo con la desestructuración usando comas para alcanzar el índice deseado:
|
||||
|
||||
```js
|
||||
const [a, b,,, c] = [1, 2, 3, 4, 5, 6];
|
||||
console.log(a, b, c); // 1, 2, 5
|
||||
console.log(a, b, c);
|
||||
```
|
||||
|
||||
La consola mostrará los valores de `a`, `b`, y `c` como `1, 2, 5`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use destructuring assignment to swap the values of `a` and `b` so that `a` receives the value stored in `b`, and `b` receives the value stored in `a`.
|
||||
Utiliza la sintaxis de desestructuración para intercambiar los valores de `a` y `b` para que `a` reciba el valor almacenado en `b`, y `b` reciba el valor almacenado en `a`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Value of `a` should be 6, after swapping.
|
||||
El valor de `a` debe ser `6`, después del intercambio.
|
||||
|
||||
```js
|
||||
assert(a === 6);
|
||||
```
|
||||
|
||||
Value of `b` should be 8, after swapping.
|
||||
El valor de `b` debe ser `8`, después del intercambio.
|
||||
|
||||
```js
|
||||
assert(b === 8);
|
||||
```
|
||||
|
||||
You should use array destructuring to swap a and b.
|
||||
Debes usar la desestructuración de arreglos para intercambiar `a` y `b`.
|
||||
|
||||
```js
|
||||
assert(/\[\s*(\w)\s*,\s*(\w)\s*\]\s*=\s*\[\s*\2\s*,\s*\1\s*\]/g.test(code));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b89367417b2b2512b4a
|
||||
title: Use Destructuring Assignment to Assign Variables from Nested Objects
|
||||
title: Usa sintaxis de desestructuración para asignar variables desde objetos anidados
|
||||
challengeType: 1
|
||||
forumTopicId: 301214
|
||||
dashedName: use-destructuring-assignment-to-assign-variables-from-nested-objects
|
||||
@ -8,9 +8,9 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-nested-objects
|
||||
|
||||
# --description--
|
||||
|
||||
You can use the same principles from the previous two lessons to destructure values from nested objects.
|
||||
Puedes usar los mismos principios de las dos lecciones anteriores para desestructurar los valores desde objetos anidados.
|
||||
|
||||
Using an object similar to previous examples:
|
||||
Usando un objeto similar a los ejemplos anteriores:
|
||||
|
||||
```js
|
||||
const user = {
|
||||
@ -21,13 +21,13 @@ const user = {
|
||||
};
|
||||
```
|
||||
|
||||
Here's how to extract the values of object properties and assign them to variables with the same name:
|
||||
Así es como se extraen los valores de propiedades de objetos y se los asigna a variables con el mismo nombre:
|
||||
|
||||
```js
|
||||
const { johnDoe: { age, email }} = user;
|
||||
```
|
||||
|
||||
And here's how you can assign an object properties' values to variables with different names:
|
||||
Y así es como se puede asignar los valores de las propiedades de un objeto a variables con diferentes nombres:
|
||||
|
||||
```js
|
||||
const { johnDoe: { age: userAge, email: userEmail }} = user;
|
||||
@ -35,11 +35,11 @@ const { johnDoe: { age: userAge, email: userEmail }} = user;
|
||||
|
||||
# --instructions--
|
||||
|
||||
Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `lowToday` and `highToday` the values of `today.low` and `today.high` from the `LOCAL_FORECAST` object.
|
||||
Reemplaza las dos asignaciones con una sintaxis de desestructuración equivalente. Todavía deben seguir asignando las variables `lowToday` y `highToday` con los valores de `today.low` y `today.high` del objeto `LOCAL_FORECAST`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should remove the ES5 assignment syntax.
|
||||
Debes eliminar la sintaxis de asignación ES5.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `lowToday` variable.
|
||||
Debes usar desestructuración para crear la variable `lowToday`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -58,7 +58,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `highToday` variable.
|
||||
Debes usar desestructuración para crear la variable `highToday`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -68,7 +68,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`lowToday` should be equal to `64` and `highToday` should be equal to `77`.
|
||||
`lowToday` debe ser igual a `64` y `highToday` debe ser igual a `77`.
|
||||
|
||||
```js
|
||||
assert(lowToday === 64 && highToday === 77);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b89367417b2b2512b49
|
||||
title: Use Destructuring Assignment to Assign Variables from Objects
|
||||
title: Usa sintaxis de desestructuración para asignar variables desde objetos
|
||||
challengeType: 1
|
||||
forumTopicId: 301215
|
||||
dashedName: use-destructuring-assignment-to-assign-variables-from-objects
|
||||
@ -8,30 +8,29 @@ dashedName: use-destructuring-assignment-to-assign-variables-from-objects
|
||||
|
||||
# --description--
|
||||
|
||||
Destructuring allows you to assign a new variable name when extracting values. You can do this by putting the new name after a colon when assigning the value.
|
||||
La desestructuración te permite asignar un nuevo nombre de variable al extraer valores. Puedes hacer esto al poner el nuevo nombre después de dos puntos al asignar el valor.
|
||||
|
||||
Using the same object from the last example:
|
||||
Usando el mismo objeto del ejemplo anterior:
|
||||
|
||||
```js
|
||||
const user = { name: 'John Doe', age: 34 };
|
||||
```
|
||||
|
||||
Here's how you can give new variable names in the assignment:
|
||||
Así es como puedes dar nuevos nombres de variables en la asignación:
|
||||
|
||||
```js
|
||||
const { name: userName, age: userAge } = user;
|
||||
// userName = 'John Doe', userAge = 34
|
||||
```
|
||||
|
||||
You may read it as "get the value of `user.name` and assign it to a new variable named `userName`" and so on.
|
||||
Puedes leerlo como "obtén el valor de `user.name` y asígnalo a una nueva variable llamada `userName`" y así sucesivamente. El valor de `userName` sería la cadena `John Doe`, y el valor de `userAge` sería el número `34`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `highToday` and `highTomorrow` the values of `today` and `tomorrow` from the `HIGH_TEMPERATURES` object.
|
||||
Reemplaza las dos asignaciones con una sintaxis de desestructuración equivalente. Todavía deben seguir asignando las variables `highToday` y `highTomorrow` con los valores de `today` y `tomorrow` del objeto `HIGH_TEMPERATURES`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should remove the ES5 assignment syntax.
|
||||
Debes eliminar la sintaxis de asignación ES5.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,7 +39,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `highToday` variable.
|
||||
Debes usar desestructuración para crear la variable `highToday`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -50,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `highTomorrow` variable.
|
||||
Debes usar desestructuración para crear la variable `highTomorrow`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -60,7 +59,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`highToday` should be equal to `77` and `highTomorrow` should be equal to `80`.
|
||||
`highToday` debe ser igual a `77` y `highTomorrow` debe ser igual a `80`.
|
||||
|
||||
```js
|
||||
assert(highToday === 77 && highTomorrow === 80);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cfa550e84205a357704ccb6
|
||||
title: Use Destructuring Assignment to Extract Values from Objects
|
||||
title: Usa sintaxis de desestructuración para extraer valores de objetos
|
||||
challengeType: 1
|
||||
forumTopicId: 301216
|
||||
dashedName: use-destructuring-assignment-to-extract-values-from-objects
|
||||
@ -8,35 +8,38 @@ dashedName: use-destructuring-assignment-to-extract-values-from-objects
|
||||
|
||||
# --description--
|
||||
|
||||
<dfn>Destructuring assignment</dfn> is special syntax introduced in ES6, for neatly assigning values taken directly from an object.
|
||||
La <dfn>sintaxis de desestructuración</dfn> es una sintaxis especial introducida en ES6, para asignar los valores directamente desde un objeto.
|
||||
|
||||
Consider the following ES5 code:
|
||||
Considera el siguiente código ES5:
|
||||
|
||||
```js
|
||||
const user = { name: 'John Doe', age: 34 };
|
||||
|
||||
const name = user.name; // name = 'John Doe'
|
||||
const age = user.age; // age = 34
|
||||
const name = user.name;
|
||||
const age = user.age;
|
||||
```
|
||||
|
||||
Here's an equivalent assignment statement using the ES6 destructuring syntax:
|
||||
`name` tendría una cadena con valor `John Doe`, y `age` tendría el número `34`.
|
||||
|
||||
Aquí hay una sentencia de asignación equivalente usando la sintaxis de desestructuración de ES6:
|
||||
|
||||
```js
|
||||
const { name, age } = user;
|
||||
// name = 'John Doe', age = 34
|
||||
```
|
||||
|
||||
Here, the `name` and `age` variables will be created and assigned the values of their respective values from the `user` object. You can see how much cleaner this is.
|
||||
De nuevo, `name` tendrá una cadena con valor `John Doe`, y `age` tendrá el número `34`.
|
||||
|
||||
You can extract as many or few values from the object as you want.
|
||||
Aquí, las variables `name` y `age` serán creadas y se asignarán los valores respectivos a partir del objeto `user`. Puedes observar que esto es mucho más limpio.
|
||||
|
||||
Puedes extraer tantos o pocos valores del objeto como desees.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables `today` and `tomorrow` the values of `today` and `tomorrow` from the `HIGH_TEMPERATURES` object.
|
||||
Reemplaza las dos asignaciones con una sintaxis de desestructuración equivalente. Todavía deben seguir asignando las variables `today` y `tomorrow` con los valores de `today` y `tomorrow` del objeto `HIGH_TEMPERATURES`.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should remove the ES5 assignment syntax.
|
||||
Debes eliminar la sintaxis de asignación ES5.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -46,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `today` variable.
|
||||
Debes usar desestructuración para crear la variable `today`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -58,7 +61,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should use destructuring to create the `tomorrow` variable.
|
||||
Debes usar desestructuración para crear la variable `tomorrow`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -70,7 +73,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`today` should be equal to `77` and `tomorrow` should be equal to `80`.
|
||||
`today` debe ser igual a `77` y `tomorrow` debe ser igual a `80`.
|
||||
|
||||
```js
|
||||
assert(today === 77 && tomorrow === 80);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8a367417b2b2512b4d
|
||||
title: Use Destructuring Assignment to Pass an Object as a Function's Parameters
|
||||
title: Utiliza sintaxis de desestructuración para pasar un objeto como parámetro de función
|
||||
challengeType: 1
|
||||
forumTopicId: 301217
|
||||
dashedName: use-destructuring-assignment-to-pass-an-object-as-a-functions-parameters
|
||||
@ -8,52 +8,52 @@ dashedName: use-destructuring-assignment-to-pass-an-object-as-a-functions-parame
|
||||
|
||||
# --description--
|
||||
|
||||
In some cases, you can destructure the object in a function argument itself.
|
||||
En algunos casos, se puede desestructurar el objeto en un propio argumento de función.
|
||||
|
||||
Consider the code below:
|
||||
Considera el siguiente código:
|
||||
|
||||
```js
|
||||
const profileUpdate = (profileData) => {
|
||||
const { name, age, nationality, location } = profileData;
|
||||
// do something with these variables
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
This effectively destructures the object sent into the function. This can also be done in-place:
|
||||
Esto desestructura efectivamente el objeto enviado a la función. Esto también se puede hacer en el lugar:
|
||||
|
||||
```js
|
||||
const profileUpdate = ({ name, age, nationality, location }) => {
|
||||
/* do something with these fields */
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
When `profileData` is passed to the above function, the values are destructured from the function parameter for use within the function.
|
||||
Cuando `profileData` es pasado a la función anterior, los valores son desestructurados desde el parámetro de función para su uso dentro de la función.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use destructuring assignment within the argument to the function `half` to send only `max` and `min` inside the function.
|
||||
Utiliza la sintaxis de desestructuración dentro del argumento de la función `half` para enviar solo `max` y `min` dentro de la función.
|
||||
|
||||
# --hints--
|
||||
|
||||
`stats` should be an `object`.
|
||||
`stats` debe ser un objeto (`object`).
|
||||
|
||||
```js
|
||||
assert(typeof stats === 'object');
|
||||
```
|
||||
|
||||
`half(stats)` should be `28.015`
|
||||
`half(stats)` debe ser `28.015`
|
||||
|
||||
```js
|
||||
assert(half(stats) === 28.015);
|
||||
```
|
||||
|
||||
Destructuring should be used.
|
||||
Se debe utilizar desestructuración.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/half=\({\w+,\w+}\)/));
|
||||
```
|
||||
|
||||
Destructured parameter should be used.
|
||||
Se debe usar un parámetro desestructurado.
|
||||
|
||||
```js
|
||||
assert(!code.match(/stats\.max|stats\.min/));
|
||||
|
@ -1,7 +1,7 @@
|
||||
---
|
||||
id: 587d7b8a367417b2b2512b4c
|
||||
title: >-
|
||||
Use Destructuring Assignment with the Rest Parameter to Reassign Array Elements
|
||||
Utiliza la sintaxis de desestructuración con el parámetro rest para reasignar elementos de un arreglo
|
||||
challengeType: 1
|
||||
forumTopicId: 301218
|
||||
dashedName: >-
|
||||
@ -10,43 +10,45 @@ dashedName: >-
|
||||
|
||||
# --description--
|
||||
|
||||
In some situations involving array destructuring, we might want to collect the rest of the elements into a separate array.
|
||||
En algunas situaciones que implican la desestructuración de arreglos, tal vez queramos recolectar el resto de elementos en un arreglo separado.
|
||||
|
||||
The result is similar to `Array.prototype.slice()`, as shown below:
|
||||
El resultado es similar a `Array.prototype.slice()`, como se muestra a continuación:
|
||||
|
||||
```js
|
||||
const [a, b, ...arr] = [1, 2, 3, 4, 5, 7];
|
||||
console.log(a, b); // 1, 2
|
||||
console.log(arr); // [3, 4, 5, 7]
|
||||
console.log(a, b);
|
||||
console.log(arr);
|
||||
```
|
||||
|
||||
Variables `a` and `b` take the first and second values from the array. After that, because of the rest parameter's presence, `arr` gets the rest of the values in the form of an array. The rest element only works correctly as the last variable in the list. As in, you cannot use the rest parameter to catch a subarray that leaves out the last element of the original array.
|
||||
La consola mostrará los valores `1, 2` y `[3, 4, 5, 7]`.
|
||||
|
||||
Las variables `a` y `b` toman el primer y segundo valor del arreglo. Después de eso, debido a la presencia del parámetro rest, `arr` obtiene el resto de los valores en forma de un arreglo. El elemento rest sólo funciona correctamente como la última variable en la lista. Por ejemplo, no puedes usar el parámetro rest para capturar un sub-arreglo que deje fuera el último elemento del arreglo original.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Use destructuring assignment with the rest parameter to perform an effective `Array.prototype.slice()` so that `arr` is a sub-array of the original array `source` with the first two elements omitted.
|
||||
Utiliza la sintaxis de desestructuración con el parámetro rest para realizar un `Array.prototype.slice()` eficaz, de tal manera que `arr` sea un sub-arreglo del arreglo original `source` con los dos primeros elementos omitidos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`arr` should be `[3,4,5,6,7,8,9,10]`
|
||||
`arr` debe ser `[3,4,5,6,7,8,9,10]`
|
||||
|
||||
```js
|
||||
assert(arr.every((v, i) => v === i + 3) && arr.length === 8);
|
||||
```
|
||||
|
||||
`source` should be `[1,2,3,4,5,6,7,8,9,10]`
|
||||
`source` debe ser `[1,2,3,4,5,6,7,8,9,10]`
|
||||
|
||||
```js
|
||||
assert(source.every((v, i) => v === i + 1) && source.length === 10);
|
||||
```
|
||||
|
||||
`Array.slice()` should not be used.
|
||||
`Array.slice()` no debe ser usado.
|
||||
|
||||
```js
|
||||
(getUserInput) => assert(!getUserInput('index').match(/slice/g));
|
||||
```
|
||||
|
||||
Destructuring on `list` should be used.
|
||||
Se debe utilizar desestructuración en `list`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b8c367417b2b2512b56
|
||||
title: Use export to Share a Code Block
|
||||
title: Utiliza la exportación para compartir un bloque de código
|
||||
challengeType: 1
|
||||
forumTopicId: 301219
|
||||
dashedName: use-export-to-share-a-code-block
|
||||
@ -8,7 +8,7 @@ dashedName: use-export-to-share-a-code-block
|
||||
|
||||
# --description--
|
||||
|
||||
Imagine a file called `math_functions.js` that contains several functions related to mathematical operations. One of them is stored in a variable, `add`, that takes in two numbers and returns their sum. You want to use this function in several different JavaScript files. In order to share it with these other files, you first need to `export` it.
|
||||
Imagina un archivo llamado `math_functions.js` que contiene varias funciones relacionadas con operaciones matemáticas. Uno de ellos se almacena en una variable, `add`, que toma dos números y devuelve su suma. Quieres utilizar esta función en varios archivos JavaScript diferentes. Para compartirlo con estos otros archivos, primero debes usar `export` (exportarlo).
|
||||
|
||||
```js
|
||||
export const add = (x, y) => {
|
||||
@ -16,7 +16,7 @@ export const add = (x, y) => {
|
||||
}
|
||||
```
|
||||
|
||||
The above is a common way to export a single function, but you can achieve the same thing like this:
|
||||
Lo anterior es una forma común de exportar una sola función, pero puedes lograr lo mismo como esto:
|
||||
|
||||
```js
|
||||
const add = (x, y) => {
|
||||
@ -26,7 +26,7 @@ const add = (x, y) => {
|
||||
export { add };
|
||||
```
|
||||
|
||||
When you export a variable or function, you can import it in another file and use it without having to rewrite the code. You can export multiple things by repeating the first example for each thing you want to export, or by placing them all in the export statement of the second example, like this:
|
||||
Cuando exportas una variable o función, puedes importarla en otro archivo y usarla sin tener que volver a escribir el código. Puedes exportar diferentes cosas al repartir el primer ejemplo para cada una de ellas si quieres exportar o al colocarlas en la declaración de exportación del segundo ejemplo. Por ejemplo:
|
||||
|
||||
```js
|
||||
export { add, subtract };
|
||||
@ -34,11 +34,11 @@ export { add, subtract };
|
||||
|
||||
# --instructions--
|
||||
|
||||
There are two string-related functions in the editor. Export both of them using the method of your choice.
|
||||
Hay dos funciones relacionadas con cadenas en el editor. Exporta ambos utilizando el método que elijas.
|
||||
|
||||
# --hints--
|
||||
|
||||
You should properly export `uppercaseString`.
|
||||
Deberías exportar correctamente `uppercaseString`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should properly export `lowercaseString`.
|
||||
Deberías exportar correctamente `lowercaseString`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b88367417b2b2512b47
|
||||
title: Use the Rest Parameter with Function Parameters
|
||||
title: Utiliza el parámetro rest con parámetros de función
|
||||
challengeType: 1
|
||||
forumTopicId: 301221
|
||||
dashedName: use-the-rest-parameter-with-function-parameters
|
||||
@ -8,51 +8,53 @@ dashedName: use-the-rest-parameter-with-function-parameters
|
||||
|
||||
# --description--
|
||||
|
||||
In order to help us create more flexible functions, ES6 introduces the <dfn>rest parameter</dfn> for function parameters. With the rest parameter, you can create functions that take a variable number of arguments. These arguments are stored in an array that can be accessed later from inside the function.
|
||||
Para ayudarnos a crear funciones más flexibles, ES6 introduce el <dfn>parámetro rest</dfn> para los parámetros de función. Con el parámetro rest, puedes crear funciones que tomen un número variable de argumentos. Estos argumentos se almacenan en un arreglo al que se puede acceder más tarde desde dentro de la función.
|
||||
|
||||
Check out this code:
|
||||
Echa un vistazo a este código:
|
||||
|
||||
```js
|
||||
function howMany(...args) {
|
||||
return "You have passed " + args.length + " arguments.";
|
||||
}
|
||||
console.log(howMany(0, 1, 2)); // You have passed 3 arguments.
|
||||
console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.
|
||||
console.log(howMany(0, 1, 2));
|
||||
console.log(howMany("string", null, [1, 2, 3], { }));
|
||||
```
|
||||
|
||||
The rest parameter eliminates the need to check the `args` array and allows us to apply `map()`, `filter()` and `reduce()` on the parameters array.
|
||||
La consola mostrará las cadenas `You have passed 3 arguments.` y `You have passed 4 arguments.`.
|
||||
|
||||
El parámetro rest elimina la necesidad de comprobar el arreglo `args` y nos permite aplicar `map()`, `filter()` y `reduce()` en el arreglo de parámetros.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Modify the function `sum` using the rest parameter in such a way that the function `sum` is able to take any number of arguments and return their sum.
|
||||
Modifica la función `sum` usando el parámetro rest de tal manera que la función `sum` sea capaz de recibir cualquier número de argumentos y devolver su suma.
|
||||
|
||||
# --hints--
|
||||
|
||||
The result of `sum(0,1,2)` should be 3
|
||||
El resultado de `sum(0,1,2)` debe ser 3
|
||||
|
||||
```js
|
||||
assert(sum(0, 1, 2) === 3);
|
||||
```
|
||||
|
||||
The result of `sum(1,2,3,4)` should be 10
|
||||
El resultado de `sum(1,2,3,4)` debe ser 10
|
||||
|
||||
```js
|
||||
assert(sum(1, 2, 3, 4) === 10);
|
||||
```
|
||||
|
||||
The result of `sum(5)` should be 5
|
||||
El resultado de `sum(5)` debe ser 5
|
||||
|
||||
```js
|
||||
assert(sum(5) === 5);
|
||||
```
|
||||
|
||||
The result of `sum()` should be 0
|
||||
El resultado de `sum()` debe ser 0
|
||||
|
||||
```js
|
||||
assert(sum() === 0);
|
||||
```
|
||||
|
||||
`sum` should be an arrow function which uses the rest parameter syntax (`...`) on the `args` parameter.
|
||||
`sum` debe ser una función flecha que utilice la sintaxis de parámetro rest (`...`) en el parámetro `args`.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/sum=\(\.\.\.args\)=>/));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7b89367417b2b2512b48
|
||||
title: Use the Spread Operator to Evaluate Arrays In-Place
|
||||
title: Utiliza el operador de propagación para evaluar los arreglos en el lugar
|
||||
challengeType: 1
|
||||
forumTopicId: 301222
|
||||
dashedName: use-the-spread-operator-to-evaluate-arrays-in-place
|
||||
@ -8,47 +8,51 @@ dashedName: use-the-spread-operator-to-evaluate-arrays-in-place
|
||||
|
||||
# --description--
|
||||
|
||||
ES6 introduces the <dfn>spread operator</dfn>, which allows us to expand arrays and other expressions in places where multiple parameters or elements are expected.
|
||||
ES6 introduce el <dfn>operador de propagación</dfn>, que nos permite expandir arreglos y otras expresiones en lugares donde se esperan múltiples parámetros o elementos.
|
||||
|
||||
The ES5 code below uses `apply()` to compute the maximum value in an array:
|
||||
El siguiente código ES5 usa `apply()` para calcular el valor máximo en un arreglo:
|
||||
|
||||
```js
|
||||
var arr = [6, 89, 3, 45];
|
||||
var maximus = Math.max.apply(null, arr); // returns 89
|
||||
var maximus = Math.max.apply(null, arr);
|
||||
```
|
||||
|
||||
We had to use `Math.max.apply(null, arr)` because `Math.max(arr)` returns `NaN`. `Math.max()` expects comma-separated arguments, but not an array. The spread operator makes this syntax much better to read and maintain.
|
||||
`maximus` tendrá un valor de `89`.
|
||||
|
||||
Tuvimos que usar `Math.max.apply(null, arr)` porque `Math.max(arr)` devuelve `NaN`. `Math.max()` espera argumentos separados por comas, pero no un arreglo. El operador de propagación hace que esta sintaxis sea más fácil de leer y mantener.
|
||||
|
||||
```js
|
||||
const arr = [6, 89, 3, 45];
|
||||
const maximus = Math.max(...arr); // returns 89
|
||||
const maximus = Math.max(...arr);
|
||||
```
|
||||
|
||||
`...arr` returns an unpacked array. In other words, it *spreads* the array. However, the spread operator only works in-place, like in an argument to a function or in an array literal. The following code will not work:
|
||||
`maximus` tendría un valor de `89`.
|
||||
|
||||
`...arr` devuelve un arreglo desempacado. En otras palabras, *propaga* el arreglo. Sin embargo, el operador de propagación sólo funciona en el lugar, como en un argumento de función o en un arreglo literal. El siguiente código no funcionará:
|
||||
|
||||
```js
|
||||
const spreaded = ...arr; // will throw a syntax error
|
||||
const spreaded = ...arr;
|
||||
```
|
||||
|
||||
# --instructions--
|
||||
|
||||
Copy all contents of `arr1` into another array `arr2` using the spread operator.
|
||||
Copia todo el contenido de `arr1` en otro arreglo `arr2` usando el operador de propagación.
|
||||
|
||||
# --hints--
|
||||
|
||||
`arr2` should be correct copy of `arr1`.
|
||||
`arr2` debe ser una copia correcta de `arr1`.
|
||||
|
||||
```js
|
||||
assert(arr2.every((v, i) => v === arr1[i]) && arr2.length);
|
||||
```
|
||||
|
||||
`...` spread operator should be used to duplicate `arr1`.
|
||||
El operador de propagación `...` debe utilizarse para duplicar `arr1`.
|
||||
|
||||
```js
|
||||
assert(code.match(/Array\(\s*\.\.\.arr1\s*\)|\[\s*\.\.\.arr1\s*\]/));
|
||||
```
|
||||
|
||||
`arr2` should remain unchanged when `arr1` is changed.
|
||||
`arr2` debe permanecer sin cambios cuando `arr1` cambie.
|
||||
|
||||
```js
|
||||
assert((arr1, arr2) => {
|
||||
|
Reference in New Issue
Block a user