Rest Parameters and Spread Synta
JavaScript Rest Parameters and Spread Syntax (JavaScript REST参数和Spread语法)
JavaScript has a range of helpful features allowing developers to work with arrays and function parameters much effortlessly. In this chapter, the rest parameters and spread syntax are covered. (JavaScript具有一系列有用的功能,允许开发人员轻松处理数组和函数参数。在本章中,将介绍REST参数和SPREAD语法。)
Rest Parameters …
Rest Parameters … (REST参数…)
The rest parameter gives you a robust way to work with an indefinite quantity of parameters. (REST参数为您提供了一种处理无限数量参数的稳健方法。)
For better understanding what rest parameter is, let’s start from the beginning. (为了更好地理解REST参数是什么,让我们从头开始。)
You can call a function with an unspecified number of arguments, no matter how it can be defined. (无论如何定义,都可以使用未指定数量的参数调用函数。)
For instance:
function multiply(x, y) {
return x * y;
}
console.log(multiply(1, 2, 3, 4, 5));
No error can occur here, because of “enormous” arguments. But, only the first two are counted in the output. (由于“巨大”的参数,此处不会发生错误。但是,输出中只计算前两个。)
You can include the rest of the parameters in the function definition using three dots, like this: …. It must be followed by the array name containing them. The literal meaning of the dots is “gather the remaining parameters into an array.” Now, let’s cover this example:
function multiplyAll(...args) {
let result = 1;
for (let arg of args){
result *= arg;
}
return result;
}
console.log(multiplyAll(1)); // 1
console.log(multiplyAll(1, 2)); // 2
console.log(multiplyAll(1, 2, 3)); // 6
You have the option of getting the first parameters as variables gathering only the remaining part. (您可以选择获取第一个参数作为仅收集剩余部分的变量。)
In the example below, the first two arguments get into variables, and the rest - into bookTitles array:
function welcomeSite(siteName, bookName, ...bookTitles) {
console.log(' Welcome to ' + siteName + '’s ' + bookName + ' book' ); // Welcome to w3cdoc’s JS book
// the rest go into bookTitles array
(//其余的放入bookTitles数组)
console.log(bookTitles[0]); // Arrays
console.log(bookTitles[1]); // Functions
console.log(bookTitles.length); // 2
}
welcomeSite("w3cdoc", "JS", "Arrays", "Functions");
Please, take into account that the rest parameters should be at the end. As they gather all the remaining arguments, there is no use in them, and they can cause an error:
function f(arg1, ...rest, arg2) { // arg2 after ...rest!!!!
// error
}
The “arguments” Variable
The “arguments” Variable (“arguments”变量)
We can distinguish a unique array-like object, called arguments. It includes all arguments by their index. (我们可以区分一个唯一的类数组对象,称为参数。它按索引包含所有参数。)
Like here:
function showSiteBooks() {
console.log(arguments.length);
console.log(arguments[0]);
console.log(arguments[1]);
}
// shows: 2, Javascript, Git
showSiteBooks("Javascript", "Git");
// shows: 1, Html, undefined (no second argument)
showSiteBooks("Html");
function showSiteBooks() {
// it's iterable
(//它是可迭代的)
for(let arg of arguments){
console.log(arg);
}
}
showSiteBooks("Javascript", "Git");
showSiteBooks("Html");
The curious thing about arguments is that although it is both array-like and iterable, it is not an array. The array methods can not work for it. So, arguments.map(…) can’t be called. Moreover, it always comprises the overall arguments. They can’t be captured partially. (参数的奇怪之处在于,虽然它既类似于数组又可迭代,但它不是数组。数组方法不能用于它。因此, arguments.map (…)不能被调用。此外,它始终包含整体论点。它们不能被部分捕获。)
It would be best if you remembered that arrow functions don’t have “arguments”. If you decide to access the object of arguments from an arrow function, you can get this:
function argFunction() {
let showArgs = () => console.log(arguments[0]);
showArgs();
}
argFunction(1); // 1
Spread Syntax
Spread Syntax (Spread语法)
The spread syntax allows an array or a string to expand in the places where zero or more arguments or elements are expected. In other words, if you have a string, an array, or an object, and you wish to use all the values, you can spread them into function calls, new objects, or new arrays with a short syntax. Although the spread syntax looks like rest parameters, also using three dots …, it does the opposite. (展开语法允许数组或字符串在需要零个或多个参数或元素的地方展开。 换句话说,如果您有一个字符串、数组或对象,并且您希望使用所有值,则可以将它们扩展为具有简短语法的函数调用、新对象或新数组。 虽然传播语法看起来像REST参数,也使用三个点…… ,但它的作用正好相反。)
Whenever you use …arr in the function call, it expands an iterable object arr to the list of arguments. (无论何时在函数调用中使用… arr ,它都会将可迭代对象arr扩展到参数列表。)
The case of Math.max looks as follows:
let arr = [6, 8, 2];
console.log(Math.max(...arr)); // 8 (spread makes array into a list of arguments)
You can pass different iterables as well, this way:
let arr1 = [2, -3, 5, 4];
let arr2 = [9, 2, -7, 2];
console.log(Math.max(...arr1, ...arr2)); // 9
You can integrate the spread syntax with normal values, as follows:
let arr1 = [2, -3, 5, 4];
let arr2 = [9, 2, -7, 2];
console.log(Math.max(3, ...arr1, 6, ...arr2, 18)); // 18
It is also desirable to use the spread syntax for merging arrays:
let arr = [5, 4, 9];
let arr2 = [6, 8, 12];
let merged = [1, ...arr, 3, ...arr2];
console.log(merged); // 1,5,4,9,3,6,8,12 (1, then arr, then 3, then arr2)
You can also use the spread syntax for turning the string into an array of characters. (您还可以使用传播语法将字符串转换为字符数组。)
Here is an example:
let str = "w3cdoc";
console.log([...str]); // W,3,D,o,c,s
The spread syntax uses iterators for gathering elements the same way as does for..of. (Spread语法使用迭代器来收集元素,方法与for.. of相同。)
The Array.from can also be used for that task, as it converts an iterable into an array, like this:
let str = "w3cdoc";
// Array.from converts an iterable into an array
console.log(Array.from(str)); // W,3,D,o,c,s
It gives the same result as […str]. (它给出的结果与[… str]相同。)
But the subtle difference between the Array.from(obj) and […obj] is that the first one operates on both iterables and array-likes, but the spread syntax can work only with iterables. (但是, Array.from (obj)和[… obj]之间的微妙区别在于,第一个对象同时对迭代对象和数组对象进行操作,但扩展语法只能对迭代对象进行操作。)
Summary
Summary (概要)
As you can notice, the three dots … in the code is either rest parameters or the spread syntax. (如您所见,代码中的三个点…要么是REST参数,要么是SPREAD语法。)
In this chapter, we represented an easy way of distinguishing between them:
Whenever the … is at the end of function parameters, it’s the “rest parameters”, gathering the rest of the arguments’ list into an array. (-只要…位于函数参数的末尾,它就是“REST参数” ,将参数列表的其余部分收集到一个数组中。)
When … is in the function call, you deal with the spread syntax, which expands an array into a list. (-当…在函数调用中时,您将处理扩展语法,该语法将数组扩展为列表。)
Together they allow navigating between an array and a list of parameters smoothly. (它们一起允许在数组和参数列表之间平滑地导航。)