我希望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
}
If you are using ES6+
you can set default parameters in the following manner:
function test (foo = 1, bar = 2) {
console.log(foo, bar);
}
test(5); // foo gets overwritten, bar remains default parameter
If you need ES5
syntax you can do it in the following manner:
function test(foo, bar) {
foo = foo || 2;
bar = bar || 0;
console.log(foo, bar);
}
test(5); // foo gets overwritten, bar remains default parameter
In the above syntax the OR
operator is used. The OR
operator always returns the first value if this can be converted to true
if not it returns the righthandside value. When the function is called with no corresponding argument the parameter variable (bar
in our example) is set to undefined
by the JS engine. undefined
Is then converted to false and thus does the OR
operator return the value 0.
如果要使用最新ECMA6
语法,请使用此命令:
function myFunction(someValue = "This is DEFAULT!") {
console.log("someValue --> ", someValue);
}
myFunction("Not A default value") // calling the function without default value
myFunction() // calling the function with default value
它被称为default function parameters
。如果未传递值或未定义,则允许使用默认值初始化形式参数。
注意:它不适用于Internet Explorer或更旧的浏览器。
为了获得最大的兼容性,请使用以下命令:
function myFunction(someValue) {
someValue = (someValue === undefined) ? "This is DEFAULT!" : someValue;
console.log("someValue --> ", someValue);
}
myFunction("Not A default value") // calling the function without default value
myFunction() // calling the function with default value
这两个函数的行为完全相同,因为每个示例都依赖于这样一个事实,即undefined
在调用该函数时如果未传递任何参数值,则参数变量将为。
按照语法
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
statements
}
您可以定义形式参数的默认值。并使用typeof函数检查未定义的值。
作为更新...使用ECMAScript 6,您可以像下面这样在函数参数声明中最终设置默认值:
function f (x, y = 7, z = 42) {
return x + y + z
}
f(1) === 50
Default Parameter Values
With ES6, you can do perhaps one of the most common idioms in JavaScript
relates to setting a default value for a function parameter. The way we’ve done this for years should look quite familiar:
function foo(x,y) {
x = x || 11;
y = y || 31;
console.log( x + y );
}
foo(); // 42
foo( 5, 6 ); // 11
foo( 5 ); // 36
foo( null, 6 ); // 17
This pattern is most used, but is dangerous when we pass values like
foo(0, 42)
foo( 0, 42 ); // 53 <-- Oops, not 42
Why? Because the 0 is falsy
, and so the x || 11 results in 11
, not the directly passed in 0. To fix this gotcha, some people will instead write the check more verbosely like this:
function foo(x,y) {
x = (x !== undefined) ? x : 11;
y = (y !== undefined) ? y : 31;
console.log( x + y );
}
foo( 0, 42 ); // 42
foo( undefined, 6 ); // 17
we can now examine a nice helpful syntax added as of ES6
to streamline the assignment of default values to missing arguments:
function foo(x = 11, y = 31) {
console.log( x + y );
}
foo(); // 42
foo( 5, 6 ); // 11
foo( 0, 42 ); // 42
foo( 5 ); // 36
foo( 5, undefined ); // 36 <-- `undefined` is missing
foo( 5, null ); // 5 <-- null coerces to `0`
foo( undefined, 6 ); // 17 <-- `undefined` is missing
foo( null, 6 ); // 6 <-- null coerces to `0`
x = 11
in a function declaration is more like x !== undefined ? x : 11
than the much more common idiom x || 11
Default Value Expressions
Function
default values can be more than just simple values like 31; they can be any valid expression, even a function call
:
function bar(val) {
console.log( "bar called!" );
return y + val;
}
function foo(x = y + 3, z = bar( x )) {
console.log( x, z );
}
var y = 5;
foo(); // "bar called"
// 8 13
foo( 10 ); // "bar called"
// 10 15
y = 6;
foo( undefined, 10 ); // 9 10
如您所见,默认值表达式是延迟计算的,这意味着它们仅在需要时以及在需要时才运行,也就是说,当参数的自变量被省略或未定义时。
默认值表达式甚至可以是内联函数表达式调用-通常称为立即调用函数表达式(IIFE)
:
function foo( x =
(function(v){ return v + 11; })( 31 )
) {
console.log( x );
}
foo(); // 42
只需使用未定义的显式比较即可。
function read_file(file, delete_after)
{
if(delete_after === undefined) { delete_after = false; }
}
该解决方案适用于js:
function read_file(file, delete_after) {
delete_after = delete_after || false;
// Code
}
在ECMAScript 6中,您实际上将能够准确地写出您拥有的东西:
function read_file(file, delete_after = false) {
// Code
}
如果不存在或,它将设置delete_after
为。您现在可以将诸如Babel这样的编译器与ES6功能一起使用。false
undefined
function read_file(file, delete_after) {
delete_after = delete_after || "my default here";
//rest of code
}
这就赋予delete_after
的价值delete_after
,如果它不是一个falsey值,否则将字符串"my default here"
。有关更多详细信息,请查看Doug Crockford对语言的调查,并查看关于“运算符”的部分。
如果你想在一个通过这种方法行不通falsey值即false
,null
,undefined
,0
或""
。如果您需要传递假值,则需要使用Tom Ritter的answer中的方法。
当处理一个函数的许多参数时,让使用者在一个对象中传递参数参数,然后将这些值与一个包含该函数默认值的对象合并通常是有用的
function read_file(values) {
values = merge({
delete_after : "my default here"
}, values || {});
// rest of code
}
// simple implementation based on $.extend() from jQuery
function merge() {
var obj, name, copy,
target = arguments[0] || {},
i = 1,
length = arguments.length;
for (; i < length; i++) {
if ((obj = arguments[i]) != null) {
for (name in obj) {
copy = obj[name];
if (target === copy) {
continue;
}
else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
使用
// will use the default delete_after value
read_file({ file: "my file" });
// will override default delete_after value
read_file({ file: "my file", delete_after: "my value" });
Yes, This will work in Javascript. You can also do that: