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
+
De nombreuses fonctions intégrées à JavaScript prennent en charge un nombre arbitraire d'arguments.
4
4
5
-
For instance:
5
+
Par exemple :
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)` -- renvoie le plus grand des arguments.
8
+
-`Object.assign(dest, src1, ..., srcN)` -- copie les propriétés de `src1..N`dans`dest`.
9
+
- ... etc.
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
+
Dans ce chapitre, nous allons apprendre à faire de même. Et, plus important encore, comment être à l'aise avec ces fonctions et ces tableaux.
12
12
13
-
## Rest parameters`...`
13
+
## Les paramètres Rest`...`
14
14
15
-
A function can be called with any number of arguments, no matter how it is defined.
15
+
Une fonction peut être appelée avec un nombre quelconque d'arguments, peu importe comment elle a été définie.
16
16
17
-
Like here:
17
+
Comme ici :
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
+
Il n'y aura pas d'erreur en raison d'arguments "excessifs". Mais bien sûr, dans le résultat, seuls les deux premiers seront comptés.
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
+
Les paramètres restants peuvent être mentionnés dans une fonction définition à trois points`...`. Ils signifient littéralement "rassemblez les paramètres restants dans un tableau".
29
29
30
-
For instance, to gather all arguments into array `args`:
30
+
Par exemple, pour rassembler tous les arguments dans un tableau `args`:
31
31
32
32
```js run
33
-
functionsumAll(...args) { // args is the name for the array
33
+
functionsumAll(...args) { // args est le nom du tableau
34
34
let sum =0;
35
35
36
36
for (let arg of args) sum += arg;
@@ -43,15 +43,15 @@ 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
+
Nous pouvons choisir d’obtenir les premiers paramètres sous forme de variables et de ne rassembler que le reste.
47
47
48
-
Here the first two arguments go into variables and the rest go into `titles`array:
48
+
Ici, les deux premiers arguments vont dans les variables et le reste dans le tableau `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="Les paramètres rest doivent être à la fin"
65
+
Les paramètres rest regroupent tous les arguments restants. Par conséquent, ce qui suit n'a pas de sens et génère une erreur :
66
66
67
67
```js
68
-
function f(arg1, ...rest, arg2) { // arg2 after ...rest ?!
68
+
function f(arg1, ...rest, arg2) { // arg2 après ...rest ?!
69
69
// error
70
70
}
71
71
```
72
72
73
-
The `...rest` must always be last.
73
+
Le `...rest` doit toujours être le dernier.
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
+
Il existe également un objet spécial array-like nommé `arguments`qui contient tous les arguments en fonction de leur index.
79
79
80
-
For instance:
80
+
Par exemple :
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
+
//c'est iterable
89
89
// for(let arg of arguments) alert(arg);
90
90
}
91
91
92
-
//shows: 2, Julius, Caesar
92
+
//affiche : 2, Julius, Caesar
93
93
showName("Julius", "Caesar");
94
94
95
-
//shows: 1, Ilya, undefined (no second argument)
95
+
//affiche : 1, Ilya, undefined (pas de second argument)
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
+
Autrefois, les paramètres rest n'existaient pas dans le langage, et utiliser les `arguments`était le seul moyen d'obtenir tous les arguments de la fonction, quel que soit leur nombre total.
100
100
101
-
And it still works, we can use it today.
101
+
Et cela fonctionne toujours, nous pouvons l'utiliser aujourd'hui.
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
+
Mais l’inconvénient est que, bien que les `arguments`ressemblent à un tableau et qu’ils soient itératifs, ce n’est pas un tableau. Il ne supporte pas les méthodes de tableau, nous ne pouvons donc pas appeler `arguments.map(...)`par exemple.
104
104
105
-
Also, it always contains all arguments. We can't capture them partially, like we did with rest parameters.
105
+
De plus, il contient toujours tous les arguments. Nous ne pouvons pas les capturer partiellement, comme nous l’avons fait avec les paramètres rest.
106
106
107
-
So when we need these features, then rest parameters are preferred.
107
+
Ainsi, lorsque nous avons besoin de ces fonctionnalités, les paramètres rest sont préférés.
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="Les fonctions fléchées n'ont pas d'`\"arguments\"`"
110
+
Si nous accédons à l'objet `arguments`à partir d'une fonction fléchée, il le prend à la fonction externe "normale".
111
111
112
-
Here's an example:
112
+
Voici un exemple :
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
+
Comme nous nous en souvenons, les fonctions fléchées n’ont pas leur propre `this`. Nous savons maintenant qu’ils n’ont pas non plus l’objet spécial `arguments`.
125
125
126
-
## Spread operator [#spread-operator]
126
+
## L'opérateur Spread [#spread-operator]
127
127
128
-
We've just seen how to get an array from the list of parameters.
128
+
Nous venons de voir comment obtenir un tableau à partir de la liste de paramètres.
129
129
130
-
But sometimes we need to do exactly the reverse.
130
+
Mais parfois, nous devons faire exactement l'inverse.
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
+
Par exemple, il existe une fonction intégrée [Math.max](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Math/max) qui renvoie le plus grand nombre d'une liste :
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
+
Maintenant, disons que nous avons un tableau `[3, 5, 1]`. Comment appelons-nous `Math.max` avec ?
139
139
140
-
Passing it "as is" won't work, because `Math.max` expects a list of numeric arguments, not a single array:
140
+
Le passer "tel quel" ne fonctionnera pas, car `Math.max` attend une liste d’arguments numériques et non un tableau :
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
+
Et nous ne pouvons sûrement pas lister manuellement les éléments dans le code `Math.max(arr[0], arr[1], arr[2])`, parce que nous pouvons ne pas savoir combien il y en a. Au fur et à mesure que notre script s'exécute, il peut y en avoir beaucoup ou pas du tout. Et ça deviendrait moche.
151
151
152
-
*Spread operator* to the rescue! It looks similar to rest parameters, also using `...`, but does quite the opposite.
152
+
*Spread operator* à la rescousse! Il ressemble aux paramètres rest, en utilisant également `...`, mais fait tout le contraire.
153
153
154
-
When `...arr` is used in the function call, it "expands" an iterable object `arr` into the list of arguments.
154
+
Quand `...arr` est utilisé dans l'appel de fonction, il "développe" un objet itérable `arr` dans la liste des arguments.
155
155
156
-
For `Math.max`:
156
+
Pour `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 transforme un tableau en une liste d'arguments)
162
162
```
163
163
164
-
We also can pass multiple iterables this way:
164
+
Nous pouvons aussi passer plusieurs iterables de cette façon :
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
+
On peut même combiner l'opérateur spread avec des valeurs normales :
Also, the spread operator can be used to merge arrays:
183
+
De plus, l'opérateur spread peut être utilisé pour fusionner des tableaux :
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, ensuite arr, ensuite 2, ensuite 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
+
Dans les exemples ci-dessus, nous avons utilisé un tableau pour illustrer l'opérateur spread, mais toutes les fonctions itérables feront l'affaire.
197
197
198
-
For instance, here we use the spread operator to turn the string into array of characters:
198
+
Par exemple, nous utilisons ici l'opérateur spread pour transformer le string en tableau de caractères :
199
199
200
200
```js run
201
201
let str = "Hello";
202
202
203
203
alert( [...str] ); // H,e,l,l,o
204
204
```
205
205
206
-
The spread operator internally uses iterators to gather elements, the same way as `for..of` does.
206
+
L’opérateur spread utilise en interne des itérateurs pour rassembler les éléments, de la même manière que `for..of`.
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
+
Donc, pour une chaine de caractères, `for..of` retourn des caractères et `...str` devient `"H","e","l","l","o"`. La liste de caractères est transmise à l'initialiseur de tableau `[...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
+
Pour cette tâche particulière, nous pourrions également utiliser `Array.from`, car il convertit un itérable (comme une chaîne de caractères) en un tableau :
211
211
212
212
```js run
213
213
let str = "Hello";
214
214
215
-
// Array.from converts an iterable into an array
215
+
// Array.from convertit un itérable en tableau
216
216
alert( Array.from(str) ); // H,e,l,l,o
217
217
```
218
218
219
-
The result is the same as `[...str]`.
219
+
Le résultat est le même que `[...str]`.
220
220
221
-
But there's a subtle difference between `Array.from(obj)` and `[...obj]`:
221
+
Mais il existe une différence subtile entre `Array.from(obj)` et `[...obj]`:
222
222
223
-
- `Array.from` operates on both array-likes and iterables.
224
-
- The spread operator operates only on iterables.
223
+
- `Array.from` fonctionne à la fois sur les tableaux et les iterables.
224
+
- L'opérateur spread ne fonctionne que sur des iterables.
225
225
226
-
So, for the task of turning something into an array, `Array.from` tends to be more universal.
226
+
Donc, pour transformer quelque chose en tableau, `Array.from` tend à être plus universel.
227
227
228
228
229
-
## Summary
229
+
## Résumé
230
230
231
-
When we see `"..."` in the code, it is either rest parameters or the spread operator.
231
+
Quand on voit `"..."` dans le code, il s’agit soit des paramètres rest ou de l’opérateur spread.
232
232
233
-
There's an easy way to distinguish between them:
233
+
Il existe un moyen facile de les distinguer :
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
+
- Lorsque `...` se trouve à la fin des paramètres de fonction, il s'agit des "paramètres rest" et rassemble le reste de la liste des arguments dans un tableau.
236
+
- Lorsque `...` est présent dans un appel de fonction ou similaire, on l'appelle "opérateur spread" (opérateur de propagation) et étend un tableau en une liste.
237
237
238
-
Use patterns:
238
+
Modèles d'utilisation :
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
+
- Les paramètres rest permettent de créer des fonctions acceptant un nombre quelconque d'arguments.
241
+
- L'opérateur spread est utilisé pour passer un tableau à des fonctions nécessitant normalement une liste d'arguments.
242
242
243
-
Together they help to travel between a list and an array of parameters with ease.
243
+
Ensemble, ils permettent de voyager facilement entre une liste et un tableau de paramètres.
244
244
245
-
All arguments of a function call are also available in "old-style" `arguments`: array-like iterable object.
245
+
Tous les arguments d'un appel de fonction sont également disponibles dans les `arguments` "à l'ancienne" : objet itérable array-like.
0 commit comments