ES6 引入 rest 参数(形式为“...变量名”),用于获取函数的多余参数,这样就不需要使用arguments对象了。rest 参数搭配的变量是一个数组,该变量将多余的参数放入数组中。(可以拿到除开始参数外的参数)
这个rest 参数和arguments不一样,它是程序员自定义的一个普通标识符,只是需要在前面加上三个点:...
function func(a, ...rest) {
console.log(a)
console.log(rest)
}
func(1) // 1 []
func(1, 2, 3, 4) //1 [2,3,4]
又比如,在前面定义2个参数
function func(a, b, ...rest) {
console.log(a, b)
console.log(rest)
}
func(1, 2) // 1 2 []
func(1, 2, 3, 4) 1 2 [3,4]
注意:剩余参数后面不能跟其他参数,否则会报错
function
func(a, ...rest, b) {
}//报错
当使用剩余参数后,函数的length属性会发生一些变化
function func(a, b, ...rest) {
}
func.length // 2
即length不包含rest,为2。
剩余参数前面可以不跟其他参数,即一个参数也没有。如
function func(...rest) {
console.log(rest)
}
func(1) // [1]
func(1, 2, 3, 4) // [1,2,3,4]
注意:rest不能和arguments一起使用,会报错
function func(...rest) {
console.log(rest)
console.log(arguments)
}
那么rest和arguments的区别是什么呢?
- arguments是一个伪数组(Array-like)
- 剩余参数是一个真正数组(Array),具有Array.prototype上的所有方法
- arguments上有callee,callee上有caller
如:
function func(a, ...rest) {
console.log(rest instanceof Array)
}
func(1, 2) // true
rest 实际应用
//求和函数
function add(...values) { let sum = 0; for (var val of values) { sum += val; } return sum; } add(2, 5, 3) // 10
上面的代码相当于以下代码
function sum(first, ...rest) {
var result = first
var i = 0
var len = rest.length
while (i < len) {
result += rest[i]
i++
}
return result
}
sum(1, 2, 3) //6
