8.ES6 函数参数默认值

 

ES6 函数参数默认值

ES6 允许给函数参数赋值初始值

1.形参初始值, 具有默认值的参数, 一般位置要靠后

1
2
3
4
5
6
7
8
9
10
11
12
let add = (a, b, c=6) => a + b + c;
let result1 = add(1, 2, 5);
console.log(result1);
// 8

let result2 = add(1, 2);
console.log(result2);
// 9

let result3 = add(1);
console.log(result3);
// NaN

2.可以与解构赋值结合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function connect({host, port="3306", username, password}) {
console.log(host);
console.log(port);
console.log(username);
console.log(password);
/**
* 127.0.0.1
* 3306
* root
* 123456
*/
}
connect({
host: "127.0.0.1",
// port: "1521",
username: "root",
password: "123456"
});