es6基础0x004:剩余参数

0x000 概述

剩余参数将没有对应形参的参数聚合成一个数组

0x001 语法

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

0x002 只聚合未对应形参参数

剩余参数只会将没有对应形参的参数聚合成一个数组, 而arguments则是包含了所有的参数。

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)}

0x003 剩余参数是数组

剩余参数始终是一个数组,而不像arguments是一个伪数组

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

0x004 解构剩余参数

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

0x005 使用babel翻译

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

翻译后

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;
  });
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章