Home > Article > Web Front-end > ECMAScript6 function remaining parameters (Rest Parameters)_javascript skills
We know that there is an arguments object inside the JS function, which can get all the actual parameters. Now ES6 has brought us a new object, which can get the parameters except the start parameters, that is, the remaining parameters (a lot of nonsense O(∩_∩)O~).
This new object is different from arguments. It is a common identifier customized by the programmer. It just needs to be preceded by three dots:...
function func(a, ...rest) { console.log(a) console.log(rest) } func(1) func(1, 2, 3, 4)
Pay attention to the second parameter rest of func, which has three dots in front. After defining it, it was called twice, and the results are as follows
You can see that the first call, rest is an empty array, and the second time is [2, 3, 4].
Another example, define 2 parameters in front
function func(a, b, ...rest) { console.log(a, b) console.log(rest) } func(1, 2) func(1, 2, 3, 4)
The output results are as follows
You should have understood the meaning of the remaining parameters through the above two examples.
There are remaining parameters, so don’t follow other parameters later, otherwise an error will be reported
function func(a, ...rest, b) { }
A parameter b is added after rest, and Firefox will report an error
When you use the remaining parameters, the length attribute of the function will undergo some changes
function func(a, b, ...rest) { } func.length // 2
That is, length does not include rest and is 2.
Some students may wonder, can there be no parameters in front of the remaining parameters? The answer is yes
function func(...rest) { console.log(rest) } func(1) // [1] func(1, 2, 3, 4) // [1,2,3,4]
The rest here actually has similar functions to arguments. Some students think that this can replace arguments? ECMAScript has this intention. Rest Parameters was already included in the abandoned ES4 (students familiar with AS3 should know this). After ES4 was abandoned, Rest Parameters was retained in ES6.
Please note that rest cannot be used with arguments and an error will be reported
function func(...rest) { console.log(rest) console.log(arguments) }
Firefox console is as follows
The difference between arguments and remaining parameters
arguments is a pseudo-array (Array-like)
The remaining parameters are a real array (Array), with all methods on Array.prototype
There is callee on arguments, and caller
on callee.
Such as
function func(a, ...rest) { console.log(rest instanceof Array) } func(1, 2) // true
Finally we end with a practical application of the remaining parameters
/* * 任意个数相加 * * **示例** * sum(1) * sum(1, 2) * sum(1, 2, 3) */ function sum(first, ...rest) { var result = first var i = 0 var len = rest.length while (i < len) { result += rest[i] i++ } return result }
The above is the entire content of this article, I hope you all like it.