我希望 JavaScript 函数具有我设置默认值的可选参数,如果未定义值,则使用该参数(如果传递了值,则忽略该参数)。在 Ruby 中,您可以这样做:
def read_file(file, delete_after = false)
# code
end
这在 JavaScript 中有效吗?
function read_file(file, delete_after = false) {
// Code
}
最佳答案
来自 ES6/ES2015 , 默认参数在语言规范中。
function read_file(file, delete_after = false) {
// Code
}
刚刚好。
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
在 ES6 中,您可以 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
···
}
// sample call using an object
myFor({ start: 3, end: 0 });
// also OK
myFor();
myFor({});
ES2015 前,
有很多方法,但这是我的首选方法——它可以让你传入任何你想要的东西,包括 false 或 null。 (typeof null == "object"
)
function foo(a, b) {
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}
关于javascript - 为 JavaScript 函数设置默认参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/894860/