Home  >  Article  >  Web Front-end  >  Example explanation of remaining parameters in ES6

Example explanation of remaining parameters in ES6

不言
不言forward
2018-11-14 15:38:301944browse

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.

Overview

The remaining parameters aggregate parameters without corresponding formal parameters into an array

Syntax

function(a, b, ...theArgs) {
}

Only aggregate parameters that do not correspond to formal parameters

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 arrays

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

Deconstructing the remaining parameters

function add(...[a, b, c]){
    return a + b +c
}
add(1, 2, 3) // 6
add(1, 2, 3) // 6

Use babelTranslation

function 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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete