Skip to content

Commit aecb287

Browse files
committed
Translation of rest-parameters-spread-operator articule
1 parent b91261d commit aecb287

File tree

1 file changed

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

1 file changed

+82
-82
lines changed
Lines changed: 82 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
# Rest parameters and spread operator
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 numero 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)` -- retorna el argumento mas grande.
8+
- `Object.assign(dest, src1, ..., srcN)` -- copia las propiedades de `src1..N` en `dest`.
9+
- ...y otros mas
1010

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.
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 como 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+
Aqui no habrá ningun error por "exceso" de argumentos. Pero, por supuesto, en el resultado solo los dos primeros serán tenidos en cuenta.
2727

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".
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,73 +43,73 @@ 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 se populan en variables y el resto populan el `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, 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.
100100

101-
And it still works, we can use it today.
101+
Y aun funciona, podemos usarlo hoy en día.
102102

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.
104104

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.
106106

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.
108108

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.
111111

112-
Here's an example:
112+
Aquí hay un ejemplo:
113113

114114
```js run
115115
function f() {
@@ -121,23 +121,23 @@ f(1); // 1
121121
```
122122
````
123123
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`.
125125
126-
## Spread operator [#spread-operator]
126+
## Operador Spread [#spread-operator]
127127
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.
129129
130-
But sometimes we need to do exactly the reverse.
130+
Pero a veces necesitamos hacer exactamente lo opuesto.
131131
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:
133133
134134
```js run
135135
alert( Math.max(3, 5, 1) ); // 5
136136
```
137137
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?
139139
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:
141141
142142
```js run
143143
let arr = [3, 5, 1];
@@ -147,21 +147,21 @@ alert( Math.max(arr) ); // NaN
147147
*/!*
148148
```
149149
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.
151151
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.
153153
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.
155155
156-
For `Math.max`:
156+
Para `Math.max`:
157157
158158
```js run
159159
let arr = [3, 5, 1];
160160
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)
162162
```
163163
164-
We also can pass multiple iterables this way:
164+
También podemos pasar múltiples iterables de esta manera:
165165
166166
```js run
167167
let arr1 = [1, -2, 3, 4];
@@ -170,7 +170,7 @@ let arr2 = [8, 3, -8, 1];
170170
alert( Math.max(...arr1, ...arr2) ); // 8
171171
```
172172
173-
We can even combine the spread operator with normal values:
173+
Incluso podemos combinar el operador spread con valores normales:
174174
175175
176176
```js run
@@ -180,7 +180,7 @@ let arr2 = [8, 3, -8, 1];
180180
alert( Math.max(1, ...arr1, 2, ...arr2, 25) ); // 25
181181
```
182182
183-
Also, the spread operator can be used to merge arrays:
183+
Además, el operador spread puede ser usado para combinar arrays:
184184
185185
```js run
186186
let arr = [3, 5, 1];
@@ -190,56 +190,56 @@ let arr2 = [8, 9, 15];
190190
let merged = [0, ...arr, 2, ...arr2];
191191
*/!*
192192
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)
194194
```
195195
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.
197197
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:
199199
200200
```js run
201-
let str = "Hello";
201+
let str = "Hola";
202202
203-
alert( [...str] ); // H,e,l,l,o
203+
alert( [...str] ); // H,o,l,a
204204
```
205205
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.
207207
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]`.
209209
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:
211211
212212
```js run
213-
let str = "Hello";
213+
let str = "Hola";
214214
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
217217
```
218218
219-
The result is the same as `[...str]`.
219+
El resultado es el mismo que `[...str]`.
220220
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]`:
222222
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.
225225
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.
227227
228228
229-
## Summary
229+
## Resumen
230230
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.
232232
233-
There's an easy way to distinguish between them:
233+
Hay una manera fácil de distinguir entre ellos:
234234
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.
237237
238-
Use patterns:
238+
Patrones de uso:
239239
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.
242242
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.
244244
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

Comments
 (0)