From ES6/ES2015 , default parameters are in the language specification.
(从ES6 / ES2015开始 ,默认参数位于语言规范中。)
function read_file(file, delete_after = false) {
// Code
}
just works.
(正常工作。)
Reference: Default Parameters - MDN
(参考: 默认参数-MDN)
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
(如果未传递任何值或未定义,则默认函数参数允许使用默认值初始化形式参数。)
You can also simulate default named parameters via destructuring :
(您还可以通过解构来模拟默认的命名参数 :)
// 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
···
}
Pre ES2015 ,
(ES2015之前的版本)
There are a lot of ways, but this is my preferred method — it lets you pass in anything you want, including false or null.
(有很多方法,但这是我的首选方法-它使您可以传递任何想要的信息,包括false或null。)
( typeof null == "object"
)(( typeof null == "object"
))
function foo(a, b) {
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…