When using special object arguments, developers can access them without specifying the parameter names. The following describes the specific application arguments object.
In function code, the special object arguments can be accessed without explicitly specifying the parameter names.
For example, in the sayHi () function, the first parameter is message. You can also access this value using arguments [0], that is, the value of the first parameter (the first parameter is at the position 0, and the second parameter is at the position 1, and so on ).
Therefore, you can rewrite the function without specifying the parameter:
function sayHi() {if (arguments[0] == "bye") {return;}alert(arguments[0]);}
Detection parameter count
You can also use the arguments object to check the number of parameters of the function and reference the arguments. length attribute.
The following code outputs the number of parameters used for each function call:
function howManyArgs() {alert(arguments.length);}howManyArgs("string", 45);howManyArgs();howManyArgs(12);
The above code displays "2", "0", and "1" in sequence ".
Note: unlike other programming languages, ECMAScript does not verify that the number of parameters passed to a function is equal to the number of parameters defined by the function. All functions defined by the developer can accept any number of parameters (according to Netscape documentation, a maximum of 255 parameters can be accepted) without causing any errors. Any missing parameters will be passed to the function as undefined, and additional functions will be ignored.
Simulate function Overloading
You can use the arguments object to determine the number of parameters passed to the function to simulate function overloading:
function doAdd() {if(arguments.length == 1) {alert(arguments[0] + 5);} else if(arguments.length == 2) {alert(arguments[0] + arguments[1]);}}
DoAdd (10); // output "15"
DoAdd (40, 20); // output "60"
When there is only one parameter, the doAdd () function adds 5 to the parameter. If two parameters exist, the two parameters are added and their sum is returned. Therefore, doAdd (10) Outputs "15", while doAdd (40, 20) Outputs "60 ".
It is not as good as heavy load, but it is enough to avoid the restriction of ECMAScript.