八、Rest参数
小于 1 分钟约 178 字
ES6
引入rest
参数,用于获取函数的实参- 用来代替
arguments
(一)ES5 获取实参的方式
- 返回一个对象
function date() {
console.log(arguments);
}
date("a", "b", "c");
// Arguments(3) ['a', 'b', 'c', callee: ƒ, Symbol(Symbol.iterator): ƒ]
(二)ES6 获取实参的方式
- 返回一个数组
- 可以使用数组的相关方法
filter
some
every
map
- ...
function date2(...args) {
console.log(args);
}
date2("a", "b", "c");
// ['a', 'b', 'c']
(三)rest 参数必须放到形参的最后
// function fn(a, ...args, b) {
// Rest parameter must be last formal parameter
function fn(a, b, ...args) {
console.log(a);
console.log(b);
console.log(args);
}
fn(1, 2, 3, 4, 5, 6, 7);
// 1
// 2
// [3, 4, 5, 6, 7]