在ES5中, 可以用aplly()把数组转化为参数。 为此ES2015 有了展开运算符(…).
比如:
let params = [1,5,4];
function sum(x = 1, y = 2, z = 3) {
return x + y + z;
}
console.log(sum(...params)); // => 10
console.log(sum.apply(undefined, params)); // => 10
函数中,展开运算符(…) 也可以代替arguments, 当作剩余参数使用
function a(x, y, ...a) {
return (x + y) * a.length;
}
// 与下面同理
function a(x, y) {
var a = Array.prototype.slice.call(arguments, 2); // 从下标为2之后的传入参数
console.log(a);
return (x + y) * a.length;
}
console.log(a(1,2,'hello',true,2)); // =>9
function a(x, y, ...a) {
return (x + y) * a[3];
}
console.log(a(1,2,'hello',true,2,5)); // => 15
获取传入的多余参数和传入多余参数使用实例就如上述代码