Copy codeThe Code is as follows:
Var f1 = function (p1, p2, p3 ){
Switch (arguments. length ){
Case 0:
Alert ("f1 without Parameters ")
Break;
Case 1:
Alert ("1 parameter version f1:" + p1)
Break;
Case 2:
Alert ("Two Parameter versions of f1:" + p1 + "," + p2)
Break;
Case 3:
Alert ("three parameter versions of f1:" + p1 + "," + p2 + "," + p3)
Break;
Default:
Alert ("more than three parameters cannot be called! ");
Break;
}
}
F1 ();
F1 ("1 ");
F1 ("a", 100 );
F1 ("1", "2", "3 ");
F1 ("1", "2", "3", "4 ")
2. Check the number of parameters
The js engine does not forcibly check the number of parameters when calling the function, so it can only be processed by itself. Example code:
Copy codeThe Code is as follows:
Var fnMustOneParam = function (p ){
// Check for parameter input
If (typeof p = "undefined "){
Alert ("fnMustOneParam must have a parameter passed in before calling (1 )! ");
Return;
}
// You can also write it like this
If (arguments. length = 0 ){
Alert ("fnMustOneParam must have a parameter passed in before it can be called (2 )! ");
Return;
}
// Number of detection Parameters
If (arguments. length! = 0 ){
Alert ("fnMustOneParam can be called with only one parameter! ");
Return;
}
// To do...
}
// FnMustOneParam (1, 3, 4 );
3. Basic Parameter type detection
The js engine does not detect the parameter type. If you want to limit the basic type of the parameter, you can use typeof to determine the basic type.
Copy codeThe Code is as follows:
Var fnString = function (s ){
If (arguments. length! = 1 ){
Alert ("the number of parameters does not match! ");
Return;
}
If (typeof s! = "String "){
Alert ("only string-type parameters can be passed in! ");
Return;
}
}
// FnString (123 );
4. Custom class parameter type detection
The method mentioned in Article 3rd can only detect the basic types of parameters. If a parameter of a custom class is used and the typeof operator number is used, only the object type detection result can be obtained, you can use the instanceof operator number to solve this problem.
Copy codeThe Code is 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 successful, p. name =" + p. name + ", p. age =" + p. age );
}
Else {
Alert ("a parameter of the Person type must be passed in before it can be called! ");
}
}
FnPerson ("asdf ");
FnPerson (new Person ('yang Guo under the bodhi tree ', 30 ))