Copy Code code as follows:
var f1 = function (P1,P2,P3) {
Switch (arguments.length) {
Case 0:
Alert ("F1 version of the argument")
Break
Case 1:
Alert ("1-parameter version of F1:" + p1)
Break
Case 2:
Alert ("2-parameter version of the F1:" + p1 + "," + p2)
Break
Case 3:
Alert ("3-parameter version of the F1:" + p1 + "," + P2 + "," + p3)
Break
Default
Alert ("Calls with more than 3 arguments are not supported!");
Break
}
}
F1 ();
F1 ("1");
F1 ("a", 100);
F1 ("1", "2", "3");
F1 ("1", "2", "3", "4")
2. Measuring the number of parameters
The JS engine also does not force a check on the number of parameters when function calls, so you can only handle it yourself, sample code:
Copy Code code as follows:
var fnmustoneparam = function (p) {
Detect any parameters passed in
if (typeof p== "undefined") {
Alert ("Fnmustoneparam must have parameters passed in to invoke (1)!");
return;
}
It can be written like this.
if (arguments.length==0) {
Alert ("Fnmustoneparam must have parameters passed in to invoke (2)!");
Return
}
Number of test parameters
if (arguments.length!=0) {
Alert ("Fnmustoneparam can only pass in one parameter call!");
Return
}
To do ...
}
Fnmustoneparam (1,3,4);
3. parameter basic type detection
JS engine also does not detect the type of parameters, if you want to make some restrictions on the basic types of parameters, you can use TypeOf to determine the basic type
Copy Code code as follows:
var fnstring = function (s) {
if (arguments.length!=1) {
Alert ("argument number does not match!");
return;
}
if (typeof s!= "string") {
Alert ("Only parameters of string type can be passed in!");
return;
}
}
Fnstring (123);
4. Custom class parameter type detection
3rd of the method mentioned, can only detect the basic types of parameters, if the parameters of the custom class, if the typeof operation symbol, can only get the type of object detection results, then you can use the instanceof operation symbol to solve
Copy Code code as follows:
function Person (name,age) {
THIS.name = name;
This.age = age;
}
function Fnperson (p) {
if (arguments.length=1 && p instanceof person) {
Alert ("Fnperson call succeeded, p.name=" + P.name + ", p.age=" + p.age);
}
else{
Alert ("Must pass in a parameter of person type to invoke!");
}
}
Fnperson ("asdf");
Fnperson (New person (' Yang over ' under the Banyan Tree, 30))