一、什么是rest参数(…rest)

ES6中引入rest参数(形式为'...变量名'),用于获取函数的多余参数。rest参数之后不能再有其他参数(即只
能是最后一个参数)

二、函数的rest参数
1、rest参数是真正意义上的数组,可以使用数组的任何方法
ES5

function fn() {
  console.log(arguments)  //[Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 }
}

fn(1,2,3,4)

ES6

function fn(...rest) {
  console.log(rest) //[ 1, 2, 3, 4, 5 ]
}

fn(1,2,3,4,5)

2、对于函数的length属性,不包含rest

function fn(a, b, ...rest) {
  
}
console.log(fn.length)  //2

3、rest参数只能作为最后一个参数,在它之后不能存在任何其他的参数,否则会报错。

function fn(a, b, ...rest) {
  console.log(a)
  console.log(b)
  console.log(rest)
}
fn(1,2,3,4,5,6)

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐