ES6扩展:剩余参数
一、剩余参数
const add = (x, y, ...args) => {
console.log(x, y, args);
};
add(); //undefined undefined
add(1); //1 undefined
add(1, 2); // 1 2
add(1, 2, 3, 4, 5); //1 2 [3, 4, 5]
剩余参数永远是个数组,即使没有值,也是空数组
二、剩余参数的注意事项
1、箭头函数的剩余参数:箭头函数的参数部分即使只有一个剩余参数,也不能省略圆括号
const add = (...args) => {};
2、使用剩余参数替代 arguments 获取实际参数
const add = (...args) => {
console.log(args);
};
add(1, 2);
3、剩余参数的位置:剩余参数只能是最后一个参数,之后不能再有其他参数,否则会报错