This article mainly introduces the relevant information about the arguments object in Javascript, which is very good and has reference value. If you need it, you can refer to all objects in js and even functions are objects, the function name is actually a variable that references the function definition object.
1. What is arguments?
The arguments in this function is very special. It is actually a built-in class array object of the function. You can use the [I] And. length arrays.
2. What is the function?
Js syntax does not support overloading! However, the arguments object can be used to simulate the Overload effect.
Arguments object: An array object automatically created in the function object to receive all parameter values.
Arguments [I]: Obtain the parameter value with the input subscript I.
Arguments. length: gets the number of input parameters!
Overload:
Multiple Functions with the same name and different parameter lists can be defined in the program,
The caller does not have to distinguish the parameters of each function,
During execution, the program automatically determines the function to be selected based on the number of input parameters.
Example:
// 1. If you input a parameter, calculate the square function sum (a) {console. log (a * a);} // If you input two parameters, sum function sum (a, B) {console. log (a + B);} sum (4 );//? Sum (4, 5 );//?
In the above example, we originally wanted the same name function sum () to output different results based on different parameters, but sum is the function name and essentially a variable,
The second will overwrite the first one, so the correct output is NaN, 9. So obviously this is not acceptable.
If arguments is used, it is much simpler.
Two examples are as follows:
// 2. function calc () {// if you input a parameter, obtain the square if (arguments. length = 1) {console. log (arguments [0] * arguments [0]);} else if (arguments. length = 2) {// If you specify two parameters, sum them to the console. log (arguments [0] + arguments [1]) ;}} calc (4); // 16 calc (4, 5 ); // 9/* 3. You can sum up multiple numbers */function add () {// arguments: [] // traverse each element in arguments, and accumulate for (var I = 0, sum = 0; IThis is the effect of JS's use of arguments overload. A simple understanding is the reuse of a function.
Arguments. length is determined by real parameters, that is, the number of parameters in the function call is determined!
The above section describes the knowledge of arguments objects in Javascript. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. I would like to thank you for your support for PHP chinnet!
For more articles about arguments objects in Javascript, refer to the PHP Chinese website!