javascript 函数参数的默认值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3672084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Default value for function parameter?
提问by user280725
So I've been doing this for as long as I can remember, but I'm curious if this is really what I should be doing. You write a function that takes a parameter, so you anticipate it to have a value, but if it doesn't, you have a good reason to default it, to say zero. What I currently do is write a helper function:
所以我从记事起就一直在做这件事,但我很好奇这是否真的是我应该做的。您编写了一个接受参数的函数,因此您预计它会有一个值,但如果没有,您就有充分的理由默认它,比如零。我目前所做的是编写一个辅助函数:
function foo() { return foo(0); };
function foo(bar) { ... };
I just ran across an instance where I did this and I looked at it oddly for a few seconds before understanding my logic behind it. I come from php where it's trivial:
我刚刚遇到了一个我这样做的实例,在理解它背后的逻辑之前,我奇怪地看了几秒钟。我来自 php,它很简单:
function foo(bar=0) { ... }
Is there a javascript alternative that I'm not aware of?
是否有我不知道的 javascript 替代方案?
回答by Anurag
You can't have overloaded functions in JavaScript. Instead, use object based initialization, or check for the values and assign a default if none supplied.
JavaScript 中不能有重载函数。相反,使用基于对象的初始化,或检查值并在未提供时分配默认值。
In your example, the second function foo(bar)will replace the first one.
在您的示例中,第二个函数foo(bar)将替换第一个函数。
Here's a function using object initialization.
这是一个使用对象初始化的函数。
function foo(config) {
extend(this, config);
}
where extendis a function that merges the config object with the current object. It is similar to the $.extendmethod in jQuery, or $extendmethod of MooTools.
whereextend是一个将配置对象与当前对象合并的函数。它类似于$.extendjQuery中的方法,或$extendMooTools的方法。
Invoke the function and pass it named key value pairs
调用函数并传递命名键值对
foo({ bar: 0 });
The other way to initialize is to look at the supplied values, and assign a default if the value is not given
另一种初始化方法是查看提供的值,如果没有给出值,则分配一个默认值
function foo(bar) {
bar = bar || 0;
}
This works as long as bar is not a falsy value. So foo(false)or foo("")will still initialize barto 0. For such cases, do an explicit check.
只要 bar 不是假值,这就会起作用。所以foo(false)orfoo("")仍然会初始化bar为0. 对于这种情况,请进行显式检查。
function foo(bar) {
bar = (typeof bar == 'undefined' ? 0 : bar);
}
回答by Annie
In JavaScript, the argument will be undefined if the user didn't pass it in. You can use the || operator to set the value of the argument if it's undefined:
在 JavaScript 中,如果用户没有传入参数,则该参数将是未定义的。您可以使用 || 如果未定义参数,则用于设置参数的值的运算符:
function foo(bar) {
bar = bar || 0;
...
}
回答by Matthew.Lothian
The simplest way I know of is test for a value and then set it to a default value if no value is found. I have not come across a catch all one liner yet, this is the best i have got.
我所知道的最简单的方法是测试一个值,如果没有找到值,则将其设置为默认值。我还没有遇到过一种全能衬里,这是我得到的最好的衬里。
If expecting a string value use this. Default will trigger on these values: [ undefined, null, "" ]
如果需要字符串值,请使用它。默认值将在这些值上触发:[ undefined, null, "" ]
function foo(str) {
str = !!str ? str : 'bar';
...
}
If expecting a number or Boolean value. This allows 0 and false as values. Default will trigger on [ undefined, null, {}, functions ]
如果需要数字或布尔值。这允许 0 和 false 作为值。默认将在 [ undefined, null, {}, functions ] 上触发
Handy for making values arguments that only accept primitive values like number, boolean and string
便于制作仅接受原始值(如数字、布尔值和字符串)的值参数
function foo(val) {
val= !!val == val || val*1 ? val : 10;
...
}
If you're looking to test for objects such as {}, There is documentation on doing this but it isn't so simple.
如果您要测试诸如 {} 之类的对象,有关于执行此操作的文档,但并非如此简单。
回答by Grant
Hopefully this answers a bit clearer for someone - I ended up using the ol' check for undefined if(typeof functionparameter !== 'undefined')as per:
希望这对某人来说回答得更清楚一些 - 我最终使用了 ol' 检查未定义,if(typeof functionparameter !== 'undefined')如下所示:
$.fn.extend({
doThing: function(stringparameter = 'FooBar!', functionparameter){
console.log('Here is your string '+stringparameter);
// Run it if it's been passed through:
if(typeof functionparameter !== 'undefined') functionparameter();
});

