We know there is a arguments object inside the JS function, you can get all the arguments. Now ES6 has brought us a new object that can get parameters other than the start parameter, that is, the remaining arguments (a lot of O (∩_∩) o~).
This new object is not the same as arguments, it is a generic identifier of the programmer's custom, but it needs to be preceded by a three point: ...
function func (A, ... rest) {
Console.log (a)
Console.log (rest)
}
func (1)
func (1, 2, 3, 4)
Note the second parameter rest of Func, which has three points ahead. After the definition is called two times, the results are as follows
When you see the first call, rest is an empty array, and the second time is [2, 3, 4].
For example, to define 2 parameters in the preceding
function Func (A, B, ... rest) {
Console.log (A, B)
Console.log (rest)
}
func (1, 2)
func (1, 2, 3, 4)
The output is as follows
The above two examples should already understand the meaning of the remaining parameters.
The rest of the parameters, so do not follow the other parameters, or it will be an error
function func (A, ... rest, b) {
}
Here, after rest, you add a parameter B,firefox will complain
When you use the remaining parameters, the length property of the function changes
function Func (A, B, ... rest) {
}
func.length//2
That is, length does not contain rest, it is 2.
There is a reunion to think, the remaining parameters can not have a parameter before it? The answer is yes.
function func (... rest) {
Console.log (rest)
}
func (1)//[1]
func (1, 2, 3, 4)//[1,2,3,4]
Here rest actual and arguments function is similar, have schoolmate thought this does not replace arguments? ECMAScript is the plan, in the abandoned ES4 have Rest Parameters (familiar with the AS3 of the classmate should understand), ES4 was abandoned, Rest Parameters was retained to ES6.
Note that rest cannot be used in conjunction with arguments and will complain
function func (... rest) {console.log (
rest)
console.log (arguments)
}
The Firefox console is as follows
The difference between arguments and remaining parameters
Arguments is a pseudo array (array-like)
The remaining argument is a true array (arrays) with all the methods on the Array.prototype
There's caller on the arguments Callee,callee.
Such as
function func (A, ... rest) {
Console.log (rest instanceof Array)
}
func (1, 2)/True
Finally, we use the actual application of the remaining parameters as an end
* * * * * Example * * SUM (
1)
* SUM (1, 2) * SUM (
1, 2, 3)/
function sum (a) ... rest) {var result
=
rest.length = 0
var len = "While"
(i < len) {
result = Rest [I]
i++
} return result
}
The above mentioned is the entire content of this article, I hope you can enjoy.