When a function is called, if a real parameter is omitted, the function automatically assigns a default value to the parameter, which greatly improves the convenience and flexibility of function calling.
When a function is called, if a real parameter is omitted, the function automatically assigns a default value to the parameter, which greatly improves the convenience and flexibility of function calling.
For example, if the string truncation function substr (string, start, length) in PHP is not specified, the function truncates the start position of the string to the end of the string by default, if length is specified, the length string starting from the start position is truncated. Therefore, if substr ('HTTP: // www.hualai.net.cn ', 11,6) is called ), the return value is hualai. If the last parameter is omitted, substr ('HTTP: // www.hualai.net.cn ', 11), hualai.net.cn is returned.
In the framework of jquery, examples (selector).html(metadata metadata is the HTML code of the element, and examples (selector).html (content) is the HTML of the element. We know that in C, we can set the default value for function parameters in the following form:
Void foo (int a, int B = 1, bool c = false );
In Java, you can use function overloading to set the default value of function parameters:
Public void foo (int ){
Foo (a, 1 );
}
Public void foo (int a, int B ){
Foo (a, B, false );
}
Public void foo (int a, int B, bool c ){
// Function content
}
In JavaScript, how do I set the default value of function parameters like jQuery? JavaScript does not assign values directly after parameters when defining functions in C language, nor does it reload functions like in Java, however, we can use an array of arguments Read-Only variables in the JavaScript method, as follows:
Function foo (){
Var a = arguments [0]? Arguments [0]: 1;
Var B = arguments [1]? Arguments [1]: false;
// Function content
}
The above is to determine whether a parameter exists, if it does not exist, the default value is attached to the variable, and we can determine the type of the parameter to achieve overloading:
Function foo (){
If (typeof arguments [0] = 'string ')
Alert ('parameter type is string ');
Else if (typeof arguments [0] = 'number ')
Alert ('parameter type is Numeric ');
}
Or
Function foo (){
If (arguments [0]. constructor = String)
Alert ('parameter type is string ');
Else if (arguments [0]. constructor = Number)
Alert ('parameter type is Numeric ');
}