Home >Web Front-end >JS Tutorial >Example explanation of remaining parameters in ES6
The content of this article is about the code explanation of the remaining parameters in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The remaining parameters aggregate parameters without corresponding formal parameters into an array
function(a, b, ...theArgs) { }
The remaining parameters will only aggregate parameters without corresponding formal parameters into an array, while arguments
contains all parameters.
function add(a, b, ...theArgs) { return {rest: theArgs, arguments} } add() // {rest: [undefined, undefined, []], arguments: Arguments(0)} add(1) // {rest: [1, undefined, []], arguments: Arguments(1)} add(1, 2) // {rest: [1, 2, []], arguments: Arguments(2)} add(1, 2, 3, 4, 5) // {rest: [1, 2, [3, 4, 5]], arguments: Arguments(5)}
The remaining parameters are always an array, unlike arguments
which is a pseudo-array
function add(...theArgs) { console.log(Array.isArray(theArgs)) theArgs.forEach((a)=>console.log(a)) console.log(Array.isArray(arguments)) Array.prototype.slice.call(arguments, add.length).forEach((a)=>console.log(a)) // 转化成数组 } add(1,2,3) // true 1 2 3 false 1, 2, 3, 4
function add(...[a, b, c]){ return a + b +c } add(1, 2, 3) // 6 add(1, 2, 3) // 6
babel
Translationfunction add(...num){ return num.reduce((n1,n2)=>n1+n2) }
After translation
function add() { for (var _len = arguments.length, num = Array(_len), _key = 0; _key < _len; _key++) { num[_key] = arguments[_key]; } return num.reduce(function (n1, n2) { return n1 + n2; }); }
The above is the detailed content of Example explanation of remaining parameters in ES6. For more information, please follow other related articles on the PHP Chinese website!