In js, everything is an object, and even a function is an object. The function name is actually a variable that refers to a function to define an object.
1. What are arguments?
The arguments in this function body are very special. They are actually a built-in array object of the function where they are located. They can use the array [i] and .length.
2. What is its function?
The js syntax does not support overloading! However, the arguments object can be used to simulate the overload effect.
arguments object: In the function object, it is automatically created to receive all parameters and value array objects.
arguments[i]: Get the parameter value passed in subscript i
arguments.length: Get the number of parameters passed in!
Overload:
Multiple functions with the same function name and different parameter list can be defined in the program.
The caller does not have to distinguish the parameters of each function.
During execution, the program automatically determines which function to choose to execute based on the number of parameters passed in.
Examples are as follows:
// 1. If the user passes in a parameter, find the square function sum(a){console.log(a*a);}//If the user passes in two parameters, find the sum function sum(a,b){console.log(a+b);}sum(4); //? sum(4,5); //?In the above example, the original intention is to let the function sum() of the same name output different results according to different parameters, but sum is the name of the function and is essentially a variable.
The second one will override the first one, so the correct output answer above is: NaN, 9. So this is obviously not possible.
If you use arguments, it will be much simpler.
The following 2 examples:
//2. function calc(){//If the user passes in a parameter, square if(arguments.length==1){console.log(arguments[0]*arguments[0]);}else if(arguments.length==2){//If the user passes in two parameters, sum console.log(arguments[0]+arguments[1]);}}calc(4); //16calc(4,5); //9 /*3. No matter how many numbers the user passes in, sum can be summed*/function add(){//arguments:[]//Transaction every element in arguments and accumulate for(var) i=0,sum=0;i<arguments.length;sum+=arguments[i++]);return sum;//Return and }console.log(add(1,2,3)); //6console.log(add(1,2,3,4,5,6)); //21This is the effect of JS using arguments overloading. A simple understanding is to reuse a function.
arguments.length is determined by actual arguments, that is, the number of parameters in the function is determined by the number of parameters in the function call!
The above is the relevant knowledge of the arguments object in Javascript introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!