You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Many JavaScript built-in functions support an arbitrary number of arguments.
3
+
Muchas funciones nativas de JavaScript soportan un numero arbitrario de argumentos.
4
4
5
-
For instance:
5
+
Por ejemplo:
6
6
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)` -- retorna el argumento mas grande.
8
+
-`Object.assign(dest, src1, ..., srcN)` -- copia las propiedades de `src1..N`en`dest`.
9
+
- ...y otros mas
10
10
11
-
In this chapter we'll learn how to do the same. And, more importantly, how to feel comfortable working with such functions and arrays.
11
+
En este capítulo aprenderemos como hacer lo mismo. Y, además, como trabajar cómodamente con dichas funciones y arrays.
12
12
13
-
## Rest parameters`...`
13
+
## Parámetros Rest`...`
14
14
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 como sea definida.
16
16
17
-
Like here:
17
+
Por ejemplo::
18
18
```js run
19
19
functionsum(a, b) {
20
20
return a + b;
@@ -23,14 +23,14 @@ function sum(a, b) {
23
23
alert( sum(1, 2, 3, 4, 5) );
24
24
```
25
25
26
-
There will be no error because of "excessive" arguments. But of course in the result only the first two will be counted.
26
+
Aqui no habrá ningun error por "exceso" de argumentos. Pero, por supuesto, en el resultado solo los dos primeros serán tenidos en cuenta.
27
27
28
-
The rest parameters can be mentioned in a function definition with three dots `...`. They 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".
29
29
30
-
For instance, to gather all arguments into array `args`:
30
+
Por ejemplo, para reunir todos los parámetros en un array `args`:
31
31
32
32
```js run
33
-
functionsumAll(...args) { // args is the name for the array
33
+
functionsumAll(...args) { // args es el nombre del array
34
34
let sum =0;
35
35
36
36
for (let arg of args) sum += arg;
@@ -43,73 +43,73 @@ alert( sumAll(1, 2) ); // 3
43
43
alert( sumAll(1, 2, 3) ); // 6
44
44
```
45
45
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.
47
47
48
-
Here the first two arguments go into variables and the rest go into`titles` array:
48
+
Aquí los primeros dos argumentos se populan en variables y el resto populan el`titles`:
````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:
66
66
67
67
```js
68
-
function f(arg1, ...rest, arg2) { // arg2 after ...rest ?!
68
+
function f(arg1, ...rest, arg2) { // arg2 despues de ...rest ?!
69
69
// error
70
70
}
71
71
```
72
72
73
-
The `...rest` must always be last.
73
+
`...rest` debe ir siempre último.
74
74
````
75
75
76
-
## The "arguments" variable
76
+
## La variable "arguments"
77
77
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.
79
79
80
-
For instance:
80
+
Por ejemplo:
81
81
82
82
```js run
83
83
functionshowName() {
84
84
alert( arguments.length );
85
85
alert( arguments[0] );
86
86
alert( arguments[1] );
87
87
88
-
//it's iterable
88
+
//arguments es iterable
89
89
// for(let arg of arguments) alert(arg);
90
90
}
91
91
92
-
//shows: 2, Julius, Caesar
93
-
showName("Julius", "Caesar");
92
+
//muestra: 2, Julio, Cesar
93
+
showName("Julio", "Cesar");
94
94
95
-
//shows: 1, Ilya, undefined (no second argument)
95
+
//muestra: 1, Ilya, undefined (no hay segundo argumento)
96
96
showName("Ilya");
97
97
```
98
98
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, no matter their total number.
99
+
Antiguamente, los parámetros rest no existían en el lenguaje, y usar`arguments`era la unica manera de obtener todos los argumentos de una función, sin importar la cantidad de ellos.
100
100
101
-
And it still works, we can use it today.
101
+
Y aun funciona, podemos usarlo hoy en día.
102
102
103
-
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.
103
+
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.
104
104
105
-
Also, it always contains all arguments. We can't capture them partially, like we did with rest parameters.
105
+
Además, siempre contiene todos los argumentos. No podemos capturarlos parcialmente, como hicimos con los parámetros rest.
106
106
107
-
So when we need these features, then rest parameters are preferred.
107
+
Por lo tanto, cuando necesitemos estas funcionalidades, los parámetros rest son preferidos.
108
108
109
-
````smart header="Arrow functions do not have`\"arguments\"`"
110
-
If we access the`arguments`object from an arrow function, it takes them from the outer "normal" function.
109
+
````smart header="Las funciones flecha no poseen`\"arguments\"`"
110
+
Si accedemos el objeto`arguments`desde una función flecha, toma su valor dela función "normal" externa.
111
111
112
-
Here's an example:
112
+
Aquí hay un ejemplo:
113
113
114
114
```js run
115
115
functionf() {
@@ -121,23 +121,23 @@ f(1); // 1
121
121
```
122
122
````
123
123
124
-
As we remember, arrow functions don't have their own `this`. Now we know they don't have the special `arguments` object either.
124
+
Como recordamos, las funciones flecha no tienen su propio `this`. Ahora sabemos que tampoco tienen el objeto especial `arguments`.
125
125
126
-
## Spread operator [#spread-operator]
126
+
## Operador Spread [#spread-operator]
127
127
128
-
We've just seen how to get an array from the list of parameters.
128
+
Acabamos de ver como obtener un array de la lista de parámetros.
129
129
130
-
But sometimes we need to do exactly the reverse.
130
+
Pero a veces necesitamos hacer exactamente lo opuesto.
131
131
132
-
For instance, there's a built-in function [Math.max](mdn:js/Math/max) that returns the greatest number from a list:
132
+
Por ejemplo, existe una función nativa [Math.max](mdn:js/Math/max) que retorna el número mas grande de una lista:
133
133
134
134
```js run
135
135
alert( Math.max(3, 5, 1) ); // 5
136
136
```
137
137
138
-
Now let's say we have an array `[3, 5, 1]`. How do we call `Math.max` with it?
138
+
Ahora bien, supongamos que tenemos un array `[3, 5, 1]`. ¿Cómo ejecutamos `Math.max` con él?
139
139
140
-
Passing it "as is" won't work, because `Math.max` expects a list of numeric arguments, not a single array:
140
+
Pasando la variable no funcionará, porque `Math.max` espera una lista de argumentos numéricos, no un único array:
141
141
142
142
```js run
143
143
let arr = [3, 5, 1];
@@ -147,21 +147,21 @@ alert( Math.max(arr) ); // NaN
147
147
*/!*
148
148
```
149
149
150
-
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.
150
+
Y seguramente no podremos manuamente listar los items en el código `Math.max(arr[0], arr[1], arr[2])`, porque tal vez no sepamos cuantos 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.
151
151
152
-
*Spread operator* to the rescue! It looks similar to rest parameters, also using `...`, but does quite the opposite.
152
+
¡*Operador Spread* al rescate! Luce similar a los parámetros rest, utilizando también `...`, pero hace exactamente lo opuesto.
153
153
154
-
When `...arr` is used in the function call, it "expands" an iterable object `arr` into the list of arguments.
154
+
Cuando `...arr` es usado en el llamado de una función, "expande" el objeto iterable `arr` en una lista de argumentos.
155
155
156
-
For `Math.max`:
156
+
Para `Math.max`:
157
157
158
158
```js run
159
159
let arr = [3, 5, 1];
160
160
161
-
alert( Math.max(...arr) ); // 5 (spread turns array into a list of arguments)
161
+
alert( Math.max(...arr) ); // 5 (spread convierte el array en una lista de argumentos)
162
162
```
163
163
164
-
We also can pass multiple iterables this way:
164
+
También podemos pasar múltiples iterables de esta manera:
165
165
166
166
```js run
167
167
let arr1 = [1, -2, 3, 4];
@@ -170,7 +170,7 @@ let arr2 = [8, 3, -8, 1];
170
170
alert( Math.max(...arr1, ...arr2) ); // 8
171
171
```
172
172
173
-
We can even combine the spread operator with normal values:
173
+
Incluso podemos combinar el operador spread con valores normales:
Also, the spread operator can be used to merge arrays:
183
+
Además, el operador spread puede ser usado para combinar arrays:
184
184
185
185
```js run
186
186
let arr = [3, 5, 1];
@@ -190,56 +190,56 @@ let arr2 = [8, 9, 15];
190
190
let merged = [0, ...arr, 2, ...arr2];
191
191
*/!*
192
192
193
-
alert(merged); // 0,3,5,1,2,8,9,15 (0, then arr, then 2, then arr2)
193
+
alert(merged); // 0,3,5,1,2,8,9,15 (0, luego arr, después 2, después arr2)
194
194
```
195
195
196
-
In the examples above we used an array to demonstrate the spread operator, but any iterable will do.
196
+
En los ejemplos de arriba utilizamos un array para demostrar el operador spread, pero cualquier iterable funcionará también.
197
197
198
-
For instance, here we use the spread operator to turn the string into array of characters:
198
+
Por ejemplo, aquí usamos el operador spread para convertir la cadena en un array de caracteres:
199
199
200
200
```js run
201
-
let str = "Hello";
201
+
let str = "Hola";
202
202
203
-
alert( [...str] ); // H,e,l,l,o
203
+
alert( [...str] ); // H,o,l,a
204
204
```
205
205
206
-
The spread operator internally uses iterators to gather elements, the same way as `for..of` does.
206
+
El operador spread utiliza internamente iteradores para iterar los elementos, de la misma manera que `for..of` hace.
207
207
208
-
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]`.
208
+
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]`.
209
209
210
-
For this particular task we could also use `Array.from`, because it converts an iterable (like a string) into an array:
210
+
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:
211
211
212
212
```js run
213
-
let str = "Hello";
213
+
let str = "Hola";
214
214
215
-
// Array.from converts an iterable into an array
216
-
alert( Array.from(str) ); // H,e,l,l,o
215
+
// Array.from convierte un iterable en un array
216
+
alert( Array.from(str) ); // H,o,l,a
217
217
```
218
218
219
-
The result is the same as `[...str]`.
219
+
El resultado es el mismo que `[...str]`.
220
220
221
-
But there's a subtle difference between `Array.from(obj)` and `[...obj]`:
221
+
Pero hay una sutil diferencia entre `Array.from(obj)` y `[...obj]`:
222
222
223
-
- `Array.from` operates on both array-likes and iterables.
224
-
- The spread operator operates only on iterables.
223
+
- `Array.from` opera con símil-arrays e iterables.
224
+
- El operador spread solo opera con iterables.
225
225
226
-
So, for the task of turning something into an array, `Array.from` tends to be more universal.
226
+
Por lo tanto, para la tarea de convertir algo en un array, `Array.from` tiende a ser mas universal.
227
227
228
228
229
-
## Summary
229
+
## Resumen
230
230
231
-
When we see `"..."` in the code, it is either rest parameters or the spread operator.
231
+
Cuando veamos `"..."` en el código, son los parámetros rest o el operador spread.
232
232
233
-
There's an easy way to distinguish between them:
233
+
Hay una manera fácil de distinguir entre ellos:
234
234
235
-
- When `...` is at the end of function parameters, it's "rest parameters" and gathers the rest of the list of arguments into an array.
236
-
- When `...` occurs in a function call or alike, it's called a "spread operator" and expands an array into a list.
235
+
- Cuando `...` se encuentra al final de los parámetros de una funcion, son los "parámetros rest" y recogen el resto de la lista de argumentos en un array.
236
+
- Cuando `...` está en el llamado de una función o similar, se llama "operador spread" y expande un array en una lista.
237
237
238
-
Use patterns:
238
+
Patrones de uso:
239
239
240
-
- Rest parameters are used to create functions that accept any number of arguments.
241
-
- The spread operator is used to pass an array to functions that normally require a list of many arguments.
240
+
- Los parámetros rest son usados para crear funciones que acepten cualquier número de argumentos.
241
+
- El operador spread es usado para pasar un array a funciones que normalmente requieren una lista de muchos argumentos.
242
242
243
-
Together they help to travel between a list and an array of parameters with ease.
243
+
Ambos ayudan a ir entre una lista y un array de parámetros con facilidad.
244
244
245
-
All arguments of a function call are also available in "old-style" `arguments`: array-like iterable object.
245
+
Todos los argumentos de un llamado a una funcion están también disponibles en el "viejo" `arguments`: un objeto símil-array iterable.
0 commit comments