ES6 introduces the REST parameter (of the form… Variable name), used to get extra arguments to a function so you don’t need to use the arguments object. The rest argument goes with a variable that puts the extra arguments into an array.
function add(. values) {
let sum = 0;
for (var val of values) {
sum += val;
}
return sum;
}
add(2.5.3) / / 10
Copy the code
The add function in the above code is a summation function that can be passed any number of arguments using the REST argument.
Here is an example of a REST parameter instead of the arguments variable.
// arguments
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
// The rest argument
const sortNumbers = (. numbers) = > numbers.sort();
Copy the code
Comparing the two ways of writing the code above, you can see that the rest parameter is written more naturally and concisely.
The Arguments object is not an array, but an array-like object. So, in order to use an Array, the method of Array must be used. The prototype. Slice. Call it first into an Array. The REST argument does not have this problem; it is a true array, and any array-specific methods can be used. Here is an example of rewriting an array push method with the rest argument.
function push(array, ... items) {
items.forEach(function(item) {
array.push(item);
console.log(item);
});
}
var a = [];
push(a, 1.2.3)
Copy the code
Note that the REST argument cannot be followed by any other argument (that is, only the last one), otherwise an error will be reported.
/ / an error
function f(a, ... b, c) {
// ...
}
Copy the code
The length property of the function, excluding the REST argument.
(function(a) {}).length / / 1
(function(. a) {}).length / / 0
(function(a, ... b) {}).length / / 1
Copy the code
Arrow functions cannot use arguments objects, which do not exist in the function body. If you do, use the REST argument instead