Javascript function variable preset
I have a function that I want to pass an argument to, however I want it to default to 0.
Is it possible todo 开发者_如何学JAVAit similarly to PHP, like:
function byMonth(export=0) {
Many thanks
Dont do this
function byMonth(export){
export = export || 0;
alert(export);
}
Edit:
The previous version has a silent bug, I'm leaving it just as an example of what NOT TO DO.
The problem is, suppose you pass the function the argument false
, it will take the default value although you actually called it with an argument.
All this other parameters will be ignored and the default will be used (because of javascript concept of falsy)
- The number zero
0
- An empty string
""
NaN
false
null
- and (obviously)
undefined
A safer way to check for the presence of the parameter is:
function byMonth(export){
if(export === undefined) export = 0;
}
Edit 2:
The previous function is not 100% secure since someone (an idiot probably) could define undefined
making the function to behave unexpectedly. This is a final, works-anywhere, bulletproof version:
function byMonth(export){
var undefined;
if(export === undefined) export = 0;
}
You can set a default inside, like this:
function byMonth(export) {
export = export || 0;
//your code
}
I'm more than 6 years late, but now with ES6, there is another solution. Pablo Fernandez said that you can set undefined
to a value and you should check like this:
function byMonth(export){
var undefined;
if(export === undefined) export = 0;
}
Well, now you can do this:
function byMonth(export){
if(export === void 0) export = 0;
}
void 0
always evaluates to the "real" undefined
.
精彩评论