How to set the default parameter values for a function in JavaScript, here are a few ways for you to refer to.
The first method:
function Example (a,b) {
var a = Arguments[0]? arguments[0]: 1;//Setting the default value of parameter A is 1
var b = arguments[1]? Arguments[1]: The default value for 2;//setting parameter B is 2 return
a+b;
}
Note that the above functions can also be written as follows:
function Example () {
var a = Arguments[0]? arguments[0]: 1;//Setting the default value for the first parameter is 1
var b = arguments[1]? Arguments[1]: 2;//set the default value of the second parameter to 2 return
a+b;
}
Call Example:
Alert (example ()); Output 3
Alert (example (10));//Output
alert (example (10,20));//Output
alert (example (null,20));//Output 20
The second method:
function Example (name,age) {
name=name| | ' Diao Cicada ';
age=age| | ;
Alert (' Hello! I am ' +name+ ', this year ' +age+ ' years old. ');
}
The function can also be written as follows:
function Example (name,age) {
if (!name) {name= ' Diao cicada ';}
if (!age) {age=21;}
Alert (' Hello! I am ' +name+ ', this year ' +age+ ' years old. ');
}
Call Example:
Example (' Harry ');//output: Hello! This is Harry, 21 years old.
example (' Harry ', 30);//output: Hello! This is Harry, 30 years old.
example (null,30);//output: Hello! I am a marten cicada, 30 years old this year.
The third approach, which is appropriate for more parametric scenarios, uses the extension of jquery:
function example (setting) {
var defaultsetting={
name: ' Little Red ', age
: ' A ',
sex: ' Woman ',
phone: ' 100866 ',
QQ: ' 100866 ',
Birthday: ' 1949.10.01 '
};
$.extend (defaultsetting,settings);
var message= ' name: ' +defaultsetting.name
+ ', sex: ' +defaultsetting.sex
+ ', Age: ' +defaultsetting.age
+ ', Tel: ' +defaultsetting.phone
+ ', QQ: ' +defaultsetting.qq
+ ', Birthday: ' +defaultsetting.birthday
+ '. ';
alert (message);
}
Call Example:
Example ({
name: ' Little Red ',
Sex: ' Female ',
Phone: ' 100866 '
});
All of the above three methods have been learned, the three methods have their advantages and disadvantages, the specific situation of the specific analysis, choose the most appropriate way to learn.