Today we look at arguments objects and properties. Arguments objects cannot be created explicitly, arguments objects are available only when the function is started. The arguments object of a function is not an array, and a single parameter is accessed in the same way as an array element. Index n is actually 0 of the arguments object ... One of the parameters of the N property.
1 functionAdd (A, b) {2Console.log (typeofarguments);3 for(varattrincharguments) {4Console.log (attr+ ":" +arguments[attr]);5 }6 returnA +b;7 }8 9Add (10,20)
As seen from the output, arguments is actually an object, not an array, and this array has 2 attributes, with property names of 0 and 1, with values of 10 and 20, respectively.
In JavaScript, the parameter list is divided into formal parameters and actual arguments. A parameter is the argument that is specified when the function is defined, which is the parameter specified when the function is called. For example, in the example above, you can
Alert (Add (10))
To invoke the function, only one parameter is specified, that is, the number of arguments is 1 and the number of formal parameters is 2. In JavaScript, there is no requirement that the number of arguments must be the same as the number of formal parameters. The above code can also be executed. Just output Nan
In practice, we can do this by first judging the number of parameters
1 functionAdd (A, b) {2 3 //Add.length can also get the number of formal parameters, but the actual use of Arguments.callee.length4 if(arguments.length==arguments.callee.length) {5 returnA +b;6}Else{7 return"Parameter Error";8 }9 Ten}
Arguments.length: Gets the number of arguments
Arguments.callee.length: Gets the number of formal parameters
Arguments.callee: Refers to the function itself
Arguments often used for recursive operations
For example, ask for a 1-to-N and
1 function FN (n) { 2 if (n==1 ) { 4 1; }else { 6 return N+arguments.callee (N- 1 " 8 " 9 alert (FN)
Result is 5050
Javascript arguments Detailed