在es6
中, (...)
可以用作声明展开和剩余参数
在es5
中,我们可以用apply()
函数把数组转化成参数。es6
也有对应的方法,展开运算符(...)
用作展开运算符时
function sum(x = 1, y = 2, z = 3) {
return x + y + z;
}
let params = [3, 4, 5];
// es5 apply() 把数组转换成参数
console.log(sum.apply(undefined, params))
// es6 展开运算符(...)把数组转换成参数
console.log(sum(...params)); => 12
用作剩余参数时
在函数中,展开运算符(...)
也可以代替arguments
,这时充当剩余参数使用
function restParam(x, y, ...a){
return (x + y) * a.length
}
console.log(restParam(1, 2, ''hello", true, 7)) => 9
不过也可以通过其他方式去实现剩余参数的功能
function restParam(x, y){
// 这里表示从下标值为2的参数开始切割,并把切割后的参数转换成数组,对于es6中的展开运算符是一个逆过程
var a = Array.prototype.slice.call(arguments, 2)
return (x + y) * a.length
}
console.log(restParam(1, 2, ''hello", true, 7)) => 9
网友评论