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

Example explanation of remaining parameters in ES6

不言
Release: 2018-11-14 15:38:30
forward
1976 people have browsed it

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) {
}
Copy after login

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)}
Copy after login

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
Copy after login

Deconstructing the remaining parameters

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

Use babelTranslation

function add(...num){
  return num.reduce((n1,n2)=>n1+n2)
}
Copy after login

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;
  });
}
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template