Remaining Parameters of ECMAScript6 function (Rest Parameters), ecmascript
We know that the JS function has an arguments object and we can get all the real parameters. Now ES6 brings us a new object, and we can get the parameters except the start parameter, that is, the remaining parameters (a lot of nonsense O (operator _ operator) O ~).
This new object is different from arguments. It is a common identifier customized by the programmer. You just need to add three points before it :...
function func(a, ...rest) { console.log(a) console.log(rest)}func(1)func(1, 2, 3, 4)
Note that the second parameter rest of func has three preceding points. After definition, the call is made twice. The results are as follows:
We can see that the first call, rest is an empty array, and the second call is [2, 3, 4].
For example, define two parameters.
function func(a, b, ...rest) { console.log(a, b) console.log(rest)}func(1, 2)func(1, 2, 3, 4)
The output result is as follows:
The preceding two examples show the meanings of the remaining parameters.
The remaining parameters are not followed by other parameters. Otherwise, an error will be reported.
function func(a, ...rest, b) { }
Here, a parameter B is added after rest. Firefox will report an error.
When you use the remaining parameters, the length attribute of the function changes.
function func(a, b, ...rest) {}func.length // 2
That is, length does not contain rest, which is 2.
Can I have none of the preceding 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 is similar to the arguments function. Do some people think this replaces arguments? ECMAScript is the plan. In the abandoned ES4, there are already Rest Parameters (which should be familiar with AS3). After ES4 is abandoned, Rest Parameters are retained to es6.
Please note that rest cannot be used with arguments and an error is reported.
function func(...rest) { console.log(rest) console.log(arguments)}
The Firefox console is as follows:
Differences between arguments and remaining Parameters
Arguments is a pseudo Array (Array-like)
The remaining parameter is a real Array with all methods on Array. prototype.
There is callee on arguments and caller on callee.
For example
function func(a, ...rest) { console.log(rest instanceof Array)}func(1, 2) // true
Finally, we end with a practical application of the remaining parameter.
/** Add any number ** example ** 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 all the content of this article. I hope you will like it.