ES6中给出了函数的默认值设置,下面简单介绍几种设置默认参数的方法
一.基本用法
- function first(x = 1, y = 2) {
- console.log("x:"+x ,"y:"+ y);
- }
- first();
- first(100);

二.与解构赋值默认值结合
- function second({x, y = 2}) {
- console.log("x:"+x ,"y:"+ y);
- }
- second({});
- second({x:100});
- second({x:100,y:200});

这种写法在传入多个形参时可以不按顺序写入,会方便很多,可是会有个问题,没有默认值时,每次都要传“{}”就会显得很麻烦,于是我们可以再设置一次默认值
三.双重默认值
- function third({x = 1 ,y = 2} = {}) {
- console.log("x:"+x ,"y:"+ y);
- }
- third();
- third({x:100,y:200});
- third({x:100});

这种写法就不会出现易错的情况啦
四.总结
以后再进行封装函数时应改用默认值设置,特别是某些多参数的函数