我希望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
}
当前回答
在ECMAScript 6中,您实际上可以编写您所拥有的内容:
function read_file(file, delete_after = false) {
// Code
}
如果delete_after不存在或未定义,则会将其设置为false。您可以在Babel等转发器上使用像今天这样的ES6功能。
有关更多信息,请参阅MDN文章。
其他回答
function helloWorld(name, symbol = '!!!') {
name = name || 'worlds';
console.log('hello ' + name + symbol);
}
helloWorld(); // hello worlds!!!
helloWorld('john'); // hello john!!!
helloWorld('john', '(>.<)'); // hello john(>.<)
helloWorld('john', undefined); // hello john!!!
helloWorld(undefined, undefined); // hello worlds!!!
为了展示我的技能(lol),即使没有下面的命名参数,也可以编写上述函数:
ES5及以上
function foo() {
a = typeof arguments[0] !== 'undefined' ? a : 42;
b = typeof arguments[1] !== 'undefined' ? b : 'default_b';
...
}
ES6及以上
function foo(...rest) {
a = typeof rest[0] !== 'undefined' ? a : 42;
b = typeof rest[1] !== 'undefined' ? b : 'default_b';
...
}
这个解决方案在js中很适用:
function read_file(file, delete_after) {
delete_after = delete_after || false;
// Code
}
作为更新。。。使用ECMAScript 6,您最终可以在函数参数声明中设置默认值,如下所示:
function f (x, y = 7, z = 42) {
return x + y + z
}
f(1) === 50
参考文件:http://es6-features.org/#DefaultParameterValues
如果您想使用最新的ECMA6语法,请使用此选项:
函数myFunction(someValue=“这是默认值!”){console.log(“someValue-->”,someValue);}myFunction(“不是默认值”)//调用没有默认值的函数myFunction()//使用默认值调用函数
它被称为默认函数参数。如果没有传递值或未定义,它允许使用默认值初始化形式参数。注意:它不适用于Internet Explorer或较旧的浏览器。
为了获得最大可能的兼容性,请使用以下选项:
函数myFunction(someValue){someValue=(someValue==未定义)?“这是默认值!”:someValue;console.log(“someValue-->”,someValue);}myFunction(“不是默认值”)//调用没有默认值的函数myFunction()//使用默认值调用函数
这两个函数具有完全相同的行为,因为这些示例依赖于这样一个事实:如果在调用该函数时没有传递任何参数值,则参数变量将是未定义的。