在es6
中, (...)
可以用作聲明展開和剩余參數(shù)
在es5
中,我們可以用apply()
函數(shù)把數(shù)組轉(zhuǎn)化成參數(shù)要出。es6
也有對應(yīng)的方法,展開運算符(...)
用作展開運算符時
function sum(x = 1, y = 2, z = 3) {
return x + y + z;
}
let params = [3, 4, 5];
// es5 apply() 把數(shù)組轉(zhuǎn)換成參數(shù)
console.log(sum.apply(undefined, params))
// es6 展開運算符(...)把數(shù)組轉(zhuǎn)換成參數(shù)
console.log(sum(...params)); => 12
用作剩余參數(shù)時
在函數(shù)中蠢笋,展開運算符(...)
也可以代替arguments
灶芝,這時充當(dāng)剩余參數(shù)使用
function restParam(x, y, ...a){
return (x + y) * a.length
}
console.log(restParam(1, 2, ''hello", true, 7)) => 9
不過也可以通過其他方式去實現(xiàn)剩余參數(shù)的功能
function restParam(x, y){
// 這里表示從下標(biāo)值為2的參數(shù)開始切割合蔽,并把切割后的參數(shù)轉(zhuǎn)換成數(shù)組板乙,對于es6中的展開運算符是一個逆過程
var a = Array.prototype.slice.call(arguments, 2)
return (x + y) * a.length
}
console.log(restParam(1, 2, ''hello", true, 7)) => 9