How to set default parameter values for functions in JavaScript (JS), here are a few ways to refer to them.
The first method:
Function Example (A, B) {var a = Arguments[0]? arguments[0]: 1;//Set the default value for parameter A to 1var B = arguments[1]? arguments[1]: 2;//Set parameter B The default value is 2return a+b;}
Note that the above functions can also be written as follows:
function Example () {var a = Arguments[0]? arguments[0]: 1;//Set the default value for the first parameter to 1var B = arguments[1]? arguments[1]: 2;//set the second parameter The default value for the number is 2return a+b;}
Invocation Example:
Alert (example ()); Output 3alert (example (10)); Output 12alert (example (10,20)); Output 30alert (example (null,20)); Output 20
The second method:
function Example (name,age) {name=name| | ' Mink Cicada '; age=age| | 21;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= ' Marten cicada ';} if (!age) {age=21;} Alert (' Hello! I am ' +name+ ', this year ' +age+ ' years old. ‘);}
Invocation Example:
Example (' Harry ');//output: Hello! I am Harry, 21 years old this year. example (' Harry ', 30);//output: Hello! I am Harry, 30 years old this year. example (null,30);//output: Hello! I am a mink cicada, 30 years old this year.
The third method, which is suitable for many parameters, uses the extension of jquery:
function example (setting) {var defaultsetting={name: ' Marten cicada ', Age: ' + ', Sex: ' Female ', Phone: ' 13611876347 ', QQ: ' 10086 ', birthday : ' 1949.10.01 '};$.extend (defaultsetting,settings); var message= ' name: ' +defaultsetting.name+ ', Gender: ' + Defaultsetting.sex+ ', Age: ' +defaultsetting.age+ ', Phone: ' +defaultsetting.phone+ ', QQ: ' +defaultsetting.qq+ ', Birthday: ' + Defaultsetting.birthday+ '. '; alert (message);}
Invocation Example:
Example ({name: ' Wang Zhaojun ', Sex: ' Female ', Phone: ' 10089 ');//output: Name: Wang Zhaojun, Gender: Female, Age: 30, Phone: 10089,qq:10086, Birthday: 1949.10.01.
Set default parameter values for JavaScript