我希望JavaScript函数具有可选的参数,我在这些参数上设置了默认值,如果未定义值,则使用这些参数(如果传递了值,则忽略这些参数)。在Ruby中,您可以这样做:
def read_file(file, delete_after = false)
# code
end
这在JavaScript中有效吗?
function read_file(file, delete_after = false) {
// Code
}
我希望JavaScript函数具有可选的参数,我在这些参数上设置了默认值,如果未定义值,则使用这些参数(如果传递了值,则忽略这些参数)。在Ruby中,您可以这样做:
def read_file(file, delete_after = false)
# code
end
这在JavaScript中有效吗?
function read_file(file, delete_after = false) {
// Code
}
当前回答
我注意到一些回答提到,使用默认参数对其他浏览器来说是不可移植的,但可以公平地指出,对于对现代JS功能支持有限的浏览器,可以使用像Babel这样的转换器将代码转换为ES5语法。
因此:
function read_file(file, delete_after = false) {
// Code
}
将被翻译成这样(在Babel REPL->中尝试https://babeljs.io/repl/):
"use strict";
function read_file(file) {
var delete_after =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
//Code...
}
当然,如果您无意使用转换,那么像其他人所演示的那样,在函数体中设置默认参数也是非常好的。
其他回答
只需使用未定义的显式比较。
function read_file(file, delete_after)
{
if(delete_after === undefined) { delete_after = false; }
}
export const getfilesize = (bytes, decimals = 2) => {
if (bytes === 0){
return '0 Bytes';
}else{
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
}
函数throwIfNoValue(){抛出新错误(“缺少参数”);}函数foo(argValue=throwIfNoValue()){返回argValue;}
这里foo()是一个函数,它有一个名为argValue的参数。如果我们在这里的函数调用中没有传递任何信息,那么将调用throwIfNoValue()函数,并将返回的结果分配给唯一的参数argValue。这就是函数调用可以用作默认参数的方式。这使得代码更加简化和可读。
此示例取自此处
从ES6/ES2015开始,默认参数在语言规范中。
function read_file(file, delete_after = false) {
// Code
}
只是起作用。
参考:默认参数-MDN
如果没有传递值或未定义,则默认函数参数允许使用默认值初始化形式参数。
在ES6中,可以通过析构函数模拟默认命名参数:
// 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。(空类型==“对象”)
function foo(a, b) {
a = typeof a !== 'undefined' ? a : 42;
b = typeof b !== 'undefined' ? b : 'default_b';
...
}
根据语法
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
statements
}
您可以定义正式参数的默认值。还可以使用typeof函数检查未定义的值。