Three methods for setting default parameter values for functions in js: js3
For how to set the default parameter values for functions in javascript, the following methods are provided for your reference.
Method 1:
Function example (a, B) {var a = arguments [0]? Arguments [0]: 1; // set the default value of parameter a to 1 var B = arguments [1]? Arguments [1]: 2; // set the default value of parameter B to 2 return 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 of the first parameter to 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 12 alert (example (10, 20 )); // output 30 alert (example (null, 20); // output 20
Method 2:
Function example (name, age) {name = name | 'mink xy'; age = age | 21; alert ('Hello! I am '+ name +', and I am '+ age +' years old. ');}
This function can also be written as follows:
Function example (name, age) {if (! Name) {name = 'mink xy';} if (! Age) {age = 21;} alert ('Hello! I am '+ name +', and I am '+ age +' years old. ');}
Call example:
Example ('wang wu'); // output: Hello! I'm Wang Wu, 21 years old. Example ('wang wu', 30); // output: Hello! I'm Wang Wu, 30 years old. Example (null, 30); // output: Hello! I'm a 30-year-old.
The third method is suitable for scenarios with many parameters. Jquery extensions are used:
Function example (setting) {var defaultSetting = {name: 'red', age: '30', sex: 'female ', phone: '123', QQ: '123 ', birthday: '2017. 10.01 '}; $. extend (defaultSetting, settings); var message = 'name: '+ defaultSetting. name + ', Gender:' + defaultSetting. sex + ', age:' + defaultSetting. age + ', tel:' + defaultSetting. phone + ', QQ:' + defaultSetting. QQ + ', birthday:' + defaultSetting. birthday + '. '; Alert (message );}
Call example:
Example ({name: 'xiaohong', sex: 'female ', phone: '000000'}); // output: name: Xiaohong, Gender: female, age: 30, tel: 100866, QQ: 100866.
Have you learned the above three methods? These three methods have their own advantages and disadvantages. You can analyze the specific situation and select the most suitable method for learning.