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 número 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)` -- 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
10
10
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.
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 cómo 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
+
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.
27
27
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".
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,71 +43,71 @@ 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 van a variables y el resto va al array `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. 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.
100
100
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.
102
102
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.
104
104
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.
106
106
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.
109
109
110
-
Here's an example:
110
+
Aquí hay un ejemplo:
111
111
112
112
```js run
113
113
functionf() {
@@ -118,25 +118,25 @@ function f() {
118
118
f(1); // 1
119
119
```
120
120
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`.
122
122
````
123
123
124
124
125
-
## Spread syntax [#spread-syntax]
125
+
## Operador Spread [#spread-operator]
126
126
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.
128
128
129
-
But sometimes we need to do exactly the reverse.
129
+
Pero a veces necesitamos hacer exactamente lo opuesto.
130
130
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:
132
132
133
133
```js run
134
134
alert( Math.max(3, 5, 1) ); // 5
135
135
```
136
136
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?
138
138
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:
140
140
141
141
```js run
142
142
let arr = [3, 5, 1];
@@ -146,21 +146,21 @@ alert( Math.max(arr) ); // NaN
146
146
*/!*
147
147
```
148
148
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.
150
150
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.
152
152
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.
154
154
155
-
For `Math.max`:
155
+
Para `Math.max`:
156
156
157
157
```js run
158
158
let arr = [3, 5, 1];
159
159
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)
161
161
```
162
162
163
-
We also can pass multiple iterables this way:
163
+
También podemos pasar múltiples iterables de esta manera:
164
164
165
165
```js run
166
166
let arr1 = [1, -2, 3, 4];
@@ -169,7 +169,7 @@ let arr2 = [8, 3, -8, 1];
169
169
alert( Math.max(...arr1, ...arr2) ); // 8
170
170
```
171
171
172
-
We can even combine the spread syntax with normal values:
172
+
Incluso podemos combinar el operador spread con valores normales:
Also, the spread syntax can be used to merge arrays:
182
+
Además, el operador spread puede ser usado para combinar arrays:
183
183
184
184
```js run
185
185
let arr = [3, 5, 1];
@@ -189,101 +189,101 @@ let arr2 = [8, 9, 15];
189
189
let merged = [0, ...arr, 2, ...arr2];
190
190
*/!*
191
191
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)
193
193
```
194
194
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.
196
196
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:
198
198
199
199
```js run
200
-
let str = "Hello";
200
+
let str = "Hola";
201
201
202
-
alert( [...str] ); // H,e,l,l,o
202
+
alert( [...str] ); // H,o,l,a
203
203
```
204
204
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.
206
206
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]`.
208
208
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:
210
210
211
211
```js run
212
-
let str = "Hello";
212
+
let str = "Hola";
213
213
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
216
216
```
217
217
218
-
The result is the same as `[...str]`.
218
+
El resultado es el mismo que `[...str]`.
219
219
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]`:
221
221
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.
224
224
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.
226
226
227
227
228
-
## Get a new copy of an array/object
228
+
## Obtener una copia de un objeto array
229
229
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)?
231
231
232
-
It is possible to do the same thing with the spread syntax.
232
+
Es posible hacer lo mismo con la sintaxis de spread
233
233
234
234
```js run
235
235
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
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.
271
271
272
272
273
-
## Summary
273
+
## Resumen
274
274
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.
276
276
277
-
There's an easy way to distinguish between them:
277
+
Hay una manera fácil de distinguir entre ellos:
278
278
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.
281
281
282
-
Use patterns:
282
+
Patrones de uso:
283
283
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.
286
286
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.
288
288
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