9.ES6 rest参数

 

ES6 rest参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// ES6 引入 rest 参数,用于获取函数的实参,用来代替 arguments
// ES5 获取实参的方式
function test1() {
console.log(arguments);
/**
* Arguments(3)
* 0: "a"
* 1: "b"
* 2: "c"
* callee: ƒ test1()
* length: 3
*/
}
test1("a", "b", "c");

// rest 参数
function test2(...args) {
console.log(args);
/**
* (3) ['i', 'j', 'k']
* 0: "i"
* 1: "j"
* 2: "k"
* length: 3
*/
}
test2("i", "j", "k");

let fn = (a, b, ...args) => {
console.log(a);
// 1
console.log(b);
// 2
console.log(args);
/**
* (4) [3, 4, 5, 6]
* 0: 3
* 1: 4
* 2: 5
* 3: 6
* length: 4
*/
}
fn(1,2,3,4,5,6);