Skip to content

Commit 3dcd7e6

Browse files
authored
Merge pull request #116 from gndelia/02-rest-parameters-spread-operator
Rest parameters and spread operator 1-6-2 Aprobado en su versión vieja, renombrado y actualizadas 10 lineas
2 parents 0b2d72a + 81879b9 commit 3dcd7e6

File tree

1 file changed

+98
-98
lines changed
  • 1-js/06-advanced-functions/02-rest-parameters-spread

1 file changed

+98
-98
lines changed
Lines changed: 98 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
# Rest parameters and spread syntax
1+
# Parámetros Rest y operador Spread
22

3-
Many JavaScript built-in functions support an arbitrary number of arguments.
3+
Muchas funciones nativas de JavaScript soportan un número arbitrario de argumentos.
44

5-
For instance:
5+
Por ejemplo:
66

7-
- `Math.max(arg1, arg2, ..., argN)` -- returns the greatest of the arguments.
8-
- `Object.assign(dest, src1, ..., srcN)` -- copies properties from `src1..N` into `dest`.
9-
- ...and so on.
7+
- `Math.max(arg1, arg2, ..., argN)` -- devuelve el argumento más grande.
8+
- `Object.assign(dest, src1, ..., srcN)` -- copia las propiedades de `src1..N` en `dest`.
9+
- ...y otros más
1010

11-
In this chapter we'll learn how to do the same. And also, how to pass arrays to such functions as parameters.
11+
En este capítulo aprenderemos como hacer lo mismo. Y, además, cómo trabajar cómodamente con dichas funciones y arrays.
1212

13-
## Rest parameters `...`
13+
## Parámetros Rest `...`
1414

15-
A function can be called with any number of arguments, no matter how it is defined.
15+
Una función puede ser llamada con cualquier número de argumentos sin importar cómo sea definida.
1616

17-
Like here:
17+
Por ejemplo::
1818
```js run
1919
function sum(a, b) {
2020
return a + b;
@@ -23,14 +23,14 @@ function sum(a, b) {
2323
alert( sum(1, 2, 3, 4, 5) );
2424
```
2525

26-
There will be no error because of "excessive" arguments. But of course in the result only the first two will be counted.
26+
Aquí no habrá ningún error por "exceso" de argumentos. Pero, por supuesto, en el resultado solo los dos primeros serán tomados en cuenta.
2727

28-
The rest of the parameters can be included in the function definition by using three dots `...` followed by the name of the array that will contain them. The dots literally mean "gather the remaining parameters into an array".
28+
El resto de los parámetros pueden ser referenciados en la definición de una función con 3 puntos `...` seguidos por el nombre del array que los contendrá. Literalmente significan "Reunir los parámetros restantes en un array".
2929

30-
For instance, to gather all arguments into array `args`:
30+
Por ejemplo, para reunir todos los parámetros en un array `args`:
3131

3232
```js run
33-
function sumAll(...args) { // args is the name for the array
33+
function sumAll(...args) { // args es el nombre del array
3434
let sum = 0;
3535

3636
for (let arg of args) sum += arg;
@@ -43,71 +43,71 @@ alert( sumAll(1, 2) ); // 3
4343
alert( sumAll(1, 2, 3) ); // 6
4444
```
4545

46-
We can choose to get the first parameters as variables, and gather only the rest.
46+
Podermos elegir obtener los primeros parámetros como variables, y juntar solo el resto.
4747

48-
Here the first two arguments go into variables and the rest go into `titles` array:
48+
Aquí los primeros dos argumentos van a variables y el resto va al array `titles`:
4949

5050
```js run
5151
function showName(firstName, lastName, ...titles) {
52-
alert( firstName + ' ' + lastName ); // Julius Caesar
52+
alert( firstName + ' ' + lastName ); // Julio Cesar
5353

54-
// the rest go into titles array
55-
// i.e. titles = ["Consul", "Imperator"]
56-
alert( titles[0] ); // Consul
57-
alert( titles[1] ); // Imperator
54+
// el resto va en el array titles
55+
// por ejemplo titles = ["Cónsul", "Emperador"]
56+
alert( titles[0] ); // Cónsul
57+
alert( titles[1] ); // Emperador
5858
alert( titles.length ); // 2
5959
}
6060

61-
showName("Julius", "Caesar", "Consul", "Imperator");
61+
showName("Julio", "Cesar", "Cónsul", "Emperador");
6262
```
6363

64-
````warn header="The rest parameters must be at the end"
65-
The rest parameters gather all remaining arguments, so the following does not make sense and causes an error:
64+
````warn header="Los parámetros rest deben ir al final"
65+
Los parámetros rest recogen todos los argumentos sobrantes, por lo que el siguiente código no tiene sentido y causa un error:
6666
6767
```js
68-
function f(arg1, ...rest, arg2) { // arg2 after ...rest ?!
68+
function f(arg1, ...rest, arg2) { // arg2 despues de ...rest ?!
6969
// error
7070
}
7171
```
7272
73-
The `...rest` must always be last.
73+
`...rest` debe ir siempre último.
7474
````
7575

76-
## The "arguments" variable
76+
## La variable "arguments"
7777

78-
There is also a special array-like object named `arguments` that contains all arguments by their index.
78+
También existe un objeto símil-array especial llamado `arguments` que contiene todos los argumentos indexados.
7979

80-
For instance:
80+
Por ejemplo:
8181

8282
```js run
8383
function showName() {
8484
alert( arguments.length );
8585
alert( arguments[0] );
8686
alert( arguments[1] );
8787

88-
// it's iterable
88+
// arguments es iterable
8989
// for(let arg of arguments) alert(arg);
9090
}
9191

92-
// shows: 2, Julius, Caesar
93-
showName("Julius", "Caesar");
92+
// muestra: 2, Julio, Cesar
93+
showName("Julio", "Cesar");
9494

95-
// shows: 1, Ilya, undefined (no second argument)
95+
// muestra: 1, Ilya, undefined (no hay segundo argumento)
9696
showName("Ilya");
9797
```
9898

99-
In old times, rest parameters did not exist in the language, and using `arguments` was the only way to get all arguments of the function. And it still works, we can find it in the old code.
99+
Antiguamente, los parámetros rest no existían en el lenguaje, y usar `arguments` era la única manera de obtener todos los argumentos de una función. Y aún funciona, podemos encontrarlo en código antiguo.
100100

101-
But the downside is that although `arguments` is both array-like and iterable, it's not an array. It does not support array methods, so we can't call `arguments.map(...)` for example.
101+
Pero la desventaja es que a pesar de que `arguments` es símil-array e iterable, no es un array. No soporta los métodos de array, no podemos ejecutar `arguments.map(...)` por ejemplo.
102102

103-
Also, it always contains all arguments. We can't capture them partially, like we did with rest parameters.
103+
Además, siempre contiene todos los argumentos. No podemos capturarlos parcialmente como hicimos con los parámetros rest.
104104

105-
So when we need these features, then rest parameters are preferred.
105+
Por lo tanto, cuando necesitemos estas funcionalidades, los parámetros rest son preferidos.
106106

107-
````smart header="Arrow functions do not have `\"arguments\"`"
108-
If we access the `arguments` object from an arrow function, it takes them from the outer "normal" function.
107+
````smart header="Las funciones flecha no poseen `\"arguments\"`"
108+
Si accedemos el objeto `arguments` desde una función flecha, toma su valor dela función "normal" externa.
109109

110-
Here's an example:
110+
Aquí hay un ejemplo:
111111

112112
```js run
113113
function f() {
@@ -118,25 +118,25 @@ function f() {
118118
f(1); // 1
119119
```
120120

121-
As we remember, arrow functions don't have their own `this`. Now we know they don't have the special `arguments` object either.
121+
Como recordamos, las funciones flecha no tienen su propio `this`. Ahora sabemos que tampoco tienen el objeto especial `arguments`.
122122
````
123123
124124
125-
## Spread syntax [#spread-syntax]
125+
## Operador Spread [#spread-operator]
126126
127-
We've just seen how to get an array from the list of parameters.
127+
Acabamos de ver cómo obtener un array de la lista de parámetros.
128128
129-
But sometimes we need to do exactly the reverse.
129+
Pero a veces necesitamos hacer exactamente lo opuesto.
130130
131-
For instance, there's a built-in function [Math.max](mdn:js/Math/max) that returns the greatest number from a list:
131+
Por ejemplo, existe una función nativa [Math.max](mdn:js/Math/max) que devuelve el número más grande de una lista:
132132
133133
```js run
134134
alert( Math.max(3, 5, 1) ); // 5
135135
```
136136
137-
Now let's say we have an array `[3, 5, 1]`. How do we call `Math.max` with it?
137+
Ahora bien, supongamos que tenemos un array `[3, 5, 1]`. ¿Cómo ejecutamos `Math.max` con él?
138138
139-
Passing it "as is" won't work, because `Math.max` expects a list of numeric arguments, not a single array:
139+
Pasando la variable no funcionará, porque `Math.max` espera una lista de argumentos numéricos, no un único array:
140140
141141
```js run
142142
let arr = [3, 5, 1];
@@ -146,21 +146,21 @@ alert( Math.max(arr) ); // NaN
146146
*/!*
147147
```
148148
149-
And surely we can't manually list items in the code `Math.max(arr[0], arr[1], arr[2])`, because we may be unsure how many there are. As our script executes, there could be a lot, or there could be none. And that would get ugly.
149+
Y seguramente no podremos listar manualmente los ítems en el código `Math.max(arr[0], arr[1], arr[2])`, porque tal vez no sepamos cuántos son. A medida que nuestro script se ejecuta, podría haber muchos elementos, o podría no haber ninguno. Y eso podría ponerse feo.
150150
151-
*Spread syntax* to the rescue! It looks similar to rest parameters, also using `...`, but does quite the opposite.
151+
¡*Operador Spread* al rescate! Es similar a los parámetros rest, también usa `...`, pero hace exactamente lo opuesto.
152152
153-
When `...arr` is used in the function call, it "expands" an iterable object `arr` into the list of arguments.
153+
Cuando `...arr` es usado en el llamado de una función, "expande" el objeto iterable `arr` en una lista de argumentos.
154154
155-
For `Math.max`:
155+
Para `Math.max`:
156156
157157
```js run
158158
let arr = [3, 5, 1];
159159
160-
alert( Math.max(...arr) ); // 5 (spread turns array into a list of arguments)
160+
alert( Math.max(...arr) ); // 5 (spread convierte el array en una lista de argumentos)
161161
```
162162
163-
We also can pass multiple iterables this way:
163+
También podemos pasar múltiples iterables de esta manera:
164164
165165
```js run
166166
let arr1 = [1, -2, 3, 4];
@@ -169,7 +169,7 @@ let arr2 = [8, 3, -8, 1];
169169
alert( Math.max(...arr1, ...arr2) ); // 8
170170
```
171171
172-
We can even combine the spread syntax with normal values:
172+
Incluso podemos combinar el operador spread con valores normales:
173173
174174
175175
```js run
@@ -179,7 +179,7 @@ let arr2 = [8, 3, -8, 1];
179179
alert( Math.max(1, ...arr1, 2, ...arr2, 25) ); // 25
180180
```
181181
182-
Also, the spread syntax can be used to merge arrays:
182+
Además, el operador spread puede ser usado para combinar arrays:
183183
184184
```js run
185185
let arr = [3, 5, 1];
@@ -189,101 +189,101 @@ let arr2 = [8, 9, 15];
189189
let merged = [0, ...arr, 2, ...arr2];
190190
*/!*
191191
192-
alert(merged); // 0,3,5,1,2,8,9,15 (0, then arr, then 2, then arr2)
192+
alert(merged); // 0,3,5,1,2,8,9,15 (0, luego arr, después 2, después arr2)
193193
```
194194
195-
In the examples above we used an array to demonstrate the spread syntax, but any iterable will do.
195+
En los ejemplos de arriba utilizamos un array para demostrar el operador spread, pero cualquier iterable funcionará también.
196196
197-
For instance, here we use the spread syntax to turn the string into array of characters:
197+
Por ejemplo, aquí usamos el operador spread para convertir la cadena en un array de caracteres:
198198
199199
```js run
200-
let str = "Hello";
200+
let str = "Hola";
201201
202-
alert( [...str] ); // H,e,l,l,o
202+
alert( [...str] ); // H,o,l,a
203203
```
204204
205-
The spread syntax internally uses iterators to gather elements, the same way as `for..of` does.
205+
El operador spread utiliza internamente iteradores para iterar los elementos, de la misma manera que `for..of` hace.
206206
207-
So, for a string, `for..of` returns characters and `...str` becomes `"H","e","l","l","o"`. The list of characters is passed to array initializer `[...str]`.
207+
Entones, para una cadena `for..of` retorna characters y `...str` se convierte en `"H","o","l","a"`. La lista de caracteres es pasada a la inicialización del array `[...str]`.
208208
209-
For this particular task we could also use `Array.from`, because it converts an iterable (like a string) into an array:
209+
Para esta tarea en particular también podríamos haber usado `Array.from`, ya que convierte un iterable (como una cadena de caracteres) en un array:
210210
211211
```js run
212-
let str = "Hello";
212+
let str = "Hola";
213213
214-
// Array.from converts an iterable into an array
215-
alert( Array.from(str) ); // H,e,l,l,o
214+
// Array.from convierte un iterable en un array
215+
alert( Array.from(str) ); // H,o,l,a
216216
```
217217
218-
The result is the same as `[...str]`.
218+
El resultado es el mismo que `[...str]`.
219219
220-
But there's a subtle difference between `Array.from(obj)` and `[...obj]`:
220+
Pero hay una sutil diferencia entre `Array.from(obj)` y `[...obj]`:
221221
222-
- `Array.from` operates on both array-likes and iterables.
223-
- The spread syntax works only with iterables.
222+
- `Array.from` opera con símil-arrays e iterables.
223+
- El operador spread solo opera con iterables.
224224
225-
So, for the task of turning something into an array, `Array.from` tends to be more universal.
225+
Por lo tanto, para la tarea de convertir algo en un array, `Array.from` tiende a ser mas universal.
226226
227227
228-
## Get a new copy of an array/object
228+
## Obtener una copia de un objeto array
229229
230-
Remember when we talked about `Object.assign()` [in the past](https://javascript.info/object#cloning-and-merging-object-assign)?
230+
¿Recuerdas cuando hablamos acerca de `Object.assign()` [anteriormente](https://javascript.info/object#cloning-and-merging-object-assign)?
231231
232-
It is possible to do the same thing with the spread syntax.
232+
Es posible hacer lo mismo con la sintaxis de spread
233233
234234
```js run
235235
let arr = [1, 2, 3];
236-
let arrCopy = [...arr]; // spread the array into a list of parameters
237-
// then put the result into a new array
236+
let arrCopy = [...arr]; // separa el array en una lista de parameters
237+
// luego pone el resultado en un nuevo array
238238
239-
// do the arrays have the same contents?
239+
// ¿los arrays tienen el mismo contenido?
240240
alert(JSON.stringify(arr) === JSON.stringify(arrCopy)); // true
241241
242-
// are the arrays equal?
243-
alert(arr === arrCopy); // false (not same reference)
242+
// ¿los arrays son iguales?
243+
alert(arr === arrCopy); // false (no es la misma referencia)
244244
245-
// modifying our initial array does not modify the copy:
245+
// modificando nuestro array inicial no modifica la copia:
246246
arr.push(4);
247247
alert(arr); // 1, 2, 3, 4
248248
alert(arrCopy); // 1, 2, 3
249249
```
250250
251-
Note that it is possible to do the same thing to make a copy of an object:
251+
Nota que es posible hacer lo mismo para hacer una copia de un objeto:
252252
253253
```js run
254254
let obj = { a: 1, b: 2, c: 3 };
255-
let objCopy = { ...obj }; // spread the object into a list of parameters
256-
// then return the result in a new object
255+
let objCopy = { ...obj }; // separa el objeto en una lista de parámetros
256+
// luego devuelve el resultado en un nuevo objeto
257257
258-
// do the objects have the same contents?
258+
// ¿tienen los objetos el mismo contenido?
259259
alert(JSON.stringify(obj) === JSON.stringify(objCopy)); // true
260260
261-
// are the objects equal?
262-
alert(obj === objCopy); // false (not same reference)
261+
// ¿son iguales los objetos?
262+
alert(obj === objCopy); // false (no es la misma referencia)
263263
264-
// modifying our initial object does not modify the copy:
264+
// modificando el objeto inicial no modifica la copia:
265265
obj.d = 4;
266266
alert(JSON.stringify(obj)); // {"a":1,"b":2,"c":3,"d":4}
267267
alert(JSON.stringify(objCopy)); // {"a":1,"b":2,"c":3}
268268
```
269269
270-
This way of copying an object is much shorter than `let objCopy = Object.assign({}, obj);` or for an array `let arrCopy = Object.assign([], arr);` so we prefer to use it whenever we can.
270+
Esta manera de copiar un objeto es mucho más corta que `let objCopy = Object.assign({}, obj);` o para un array `let arrCopy = Object.assign([], arr);` por lo que preferimos usarla siempre que podemos.
271271
272272
273-
## Summary
273+
## Resumen
274274
275-
When we see `"..."` in the code, it is either rest parameters or the spread syntax.
275+
Cuando veamos `"..."` en el código, son los parámetros rest o el operador spread.
276276
277-
There's an easy way to distinguish between them:
277+
Hay una manera fácil de distinguir entre ellos:
278278
279-
- When `...` is at the end of function parameters, it's "rest parameters" and gathers the rest of the list of arguments into an array.
280-
- When `...` occurs in a function call or alike, it's called a "spread syntax" and expands an array into a list.
279+
- Cuando `...` se encuentra al final de los parámetros de una función, son los "parámetros rest" y recogen el resto de la lista de argumentos en un array.
280+
- Cuando `...` está en el llamado de una función o similar, se llama "operador spread" y expande un array en una lista.
281281
282-
Use patterns:
282+
Patrones de uso:
283283
284-
- Rest parameters are used to create functions that accept any number of arguments.
285-
- The spread syntax is used to pass an array to functions that normally require a list of many arguments.
284+
- Los parámetros rest son usados para crear funciones que acepten cualquier número de argumentos.
285+
- El operador spread es usado para pasar un array a funciones que normalmente requieren una lista de muchos argumentos.
286286
287-
Together they help to travel between a list and an array of parameters with ease.
287+
Ambos ayudan a ir entre una lista y un array de parámetros con facilidad.
288288
289-
All arguments of a function call are also available in "old-style" `arguments`: array-like iterable object.
289+
Todos los argumentos de un llamado a una función están también disponibles en el "viejo" `arguments`: un objeto símil-array iterable.

0 commit comments

Comments
 (0)