I don't know what is the best way to write it and how to... I have a function like
function myFunc(myVal1, myVal2){/*... various things ...*/};
where myVal1 and myVal2 are numbers
Sometimes I want to be able to recall the function passing only one parameter just by calling myFunc(myVal1). Doing so I want that myVal2 would have a standard value, if not declared, of 0.
I was thinking to write something
function myFunc(myVal1, myVal2){
if(myVal2 == NaN)
myVal2 = 0;
}
}
But I don't believe that it is the right way to do开发者_StackOverflow社区 it. Thx very much for the help!
Arguments that are not set have type undefined, test for it like this.
function myFunc(myVal1, myVal2){
if(typeof myVal2 == "undefined")
myVal2 = 0;
//the rest of the function goes here
}
function myFunc(myVal1, myVal2){
// if myVal2 is defined, keep the value, otherwise assign 0
myVal2 = myVal2 || 0;
}
should do the trick.
more ways to Rome (besides typeof myVal2 == "undefined"
):
function myFunc(myVal1, myVal2){
// if myVal2 is defined, keep the value, otherwise assign 0
// using a ternary operator
var myVal2check = myVal2 ? myVal2 : 0;
}
function myFunc(myVal1, myVal2){
// if myVal2 is defined, keep the value, otherwise assign 0
// if myVal2 needs to be an integer
myVal2 = parseInt(myVal2,10) || 0;
}
function myFunc(myVal1, myVal2){
// if myVal2 is defined, keep the value, otherwise assign 0
// using a regexp to determine the 'undefinedness'
var myVal2check = String(myVal2).match(/undef/i) ? myVal2 : 0;
}
and finally, especially for David Mårtensson
function myFunc(myVal1){
// no myVal2 defined in the parameter section
var myVal2check = window.myVal2 ? myVal2 : 0;
}
if (!myVal2) {
myVal2 = 0;
}
If you want myVal2 to default to anything other than 0, you have to be more explicit, as 0 evaluates to false. So:
if (!myVal2===undefined) {
myVal2 = 3;
}
精彩评论