什么是 rest 参数?
一、什么是rest参数(…rest)ES6中引入rest参数(形式为'...变量名'),用于获取函数的多余参数。rest参数之后不能再有其他参数(即只能是最后一个参数)。二、函数的rest参数1、rest参数是真正意义上的数组,可以使用数组的任何方法ES5function fn() {console.log(arguments)//[Arguments] { '0': 1, '1': 2, '2'
·
一、什么是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)
更多推荐
已为社区贡献22条内容
所有评论(0)