JS:函数的参数的默认值 [英] JS: functions arguments default values
问题描述
在某些语言可以为函数的参数设置默认值:
In some languages you can set default values for function's arguments:
function Foo(arg1 = 50, arg2 = 'default') {
//...
}
你是怎么做到这在JavaScript中?
How do you do it in JavaScript?
推荐答案
在JavaScript中,任何未设置给定值未定义
。这意味着,如果你想为一个功能设置默认值,你的第一线需要做个检查,看看如果这些值没有定义:
In JavaScript, anything that isn't set is given the value undefined
. This means that if you want to set default values for a function, your first line needs to be a check to see if those values aren't defined:
function Foo(arg1, arg2) {
if (typeof(arg1) === "undefined") { arg1 = 50; }
if (typeof(arg2) === "undefined") { arg2 = "default"; }
}
如果你知道这些值将大致什么,你可以采取一些捷径的:
You can take a bit of a short cut if you know roughly what those values will be:
function Foo(arg1, arg2) {
arg1 = arg1 || 50;
arg2 = arg2 || "default";
}
但是,如果这些参数是falsy,他们将被替换。这意味着,如果ARG1是一个空字符串,空
,未定义
,假
或 0
它会被改为50,所以要小心,如果你选择使用它。
However, if those arguments are falsy, they'll be replaced. This means that if arg1 is an empty string, null
, undefined
, false
or 0
it'll be changed to 50, so be careful if you chose to use it
这篇关于JS:函数的参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!