从ES6 / ES2015开始,默认参数在语言规范中。
function read_file(file, delete_after = false) {
// Code
}
正常工作。
如果 传递 或 则默认函数参数允许使用默认值初始化形式参数。
您还可以通过解构来模拟默认的命名参数:
// the `= {}` below lets you call the function without any parameters
function myFor({ start = 5, end = 1, step = -1 } = {}) { // (A)
// Use the variables `start`, `end` and `step` here
···
}
,
有很多方法,但这是我的首选方法-它使您可以传递所需的任何内容,包括false或null。(typeof null == "object"
)
function foo(a, b) {
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}