参数默认值
1. 首先, 来看一下 es5 中的函数默认值
- var a = a || 10;
- var b = b || "none"
- // 当 a 的值或者 b 的值为 undefined 时, 根据逻辑或运算的特性, 将会返回后一个值, 因而实现默认值
- function sum (a, b) {
- a = a || 10;
- b = b || 5;
- return a + b;
- }
- sum(); // 15
2.es6 中提供了一个新的函数默认值的方式, 外界传入的参数会依次赋值给函数中的参数
- function sum (a = 10, b = 5) {
- return a + b;
- }
- console.log(sum(1, 2)); // 3
- console.log(sum(5)); // 10
- console.log(sum()); // 15
- // 当需要第一个参数使用默认值, 而指定第二个参数时, 需要显式指定第一个参数值为 undefined
- // 需要注意, 当显式指定参数为 null 时, 是不会使用默认值的
- console.log(undefined, 10); // 20
- 2019-03-15 23:46:25
来源: http://www.bubuko.com/infodetail-2988879.html