When we do front-end development involves Javascript, we may encounter Javascript Functions with unfixed parameters, such as exp (a), exp (a, B ), it must be noted that the function names are the same
When we do front-end development involves Javascript, we may encounter Javascript Functions with unfixed parameters, such as exp (a), exp (a, B ), it must be noted that the function name is the same, but the input parameters are different. We may think like this: define two functions, one containing only one function, and the other has two functions. However, writing functions in Javascript cannot have the same name. What should we do? The following describes a method.
For example, to sum two numbers, we can encapsulate the following function:
| 123 |
Functionsum (a, B) {returna + B ;} |
But what if we want to sum three numbers? That's it.
| 123 |
Functionsum (a, B, c) {returna + B + c ;} |
But what if we want to sum up eight numbers or more? It is impossible for us to write it like this all the time, so we need a function that can process different numbers of parameters. For example, if we take the sum, when we pass in two parameters, we can sum two numbers, when six parameters are input, the number of six parameters can be summed. Therefore, the variable parameter function is introduced here.
Inside the JavaScript function, you can use an object named arguments, which contains all the parameters passed to the function when calling the function. Although arguments is not an array, but we can use it as an array. Of course, we can also use a subscript. argument [0] indicates the first parameter accepted, arguments [1] indicates the second accepted parameter, and so on. In addition, the arguments object has a length attribute that can be used to represent the number of parameters. Its usage is arguments. length.
Let's write a function that can process variable parameters.
| 12345678 |
Functionsum () {varresult = 0; vari = 0; for (I; I result + = arguments [I]; // arguments [I] indicates the I parameter} returnresult ;} |
OK. Let's test the code as a whole:
Evaluate the sum of any number of Javascript variable parameters
| 123456789101112131415161718192021222324252627282930 |
Js Variable Parameter Function-evaluate the sum of any number |