JS and PHP in the function of the reference is a little different, php-shaped participation in the number of arguments to match, and JS more flexible, you can pass the parameters, the actual parameters than the formal parameters or more will not be an error.
Arguments do not complain more than formal parameters
function Say (a) {
alert (a);
}
Say (' Joan Blog ', ' Web Technology blog ');
Execution results
Let's take a look at the results of more formal parameters than actual parameters.
function Say (a,b) {
alert (' A value is ' +a+ ' \nb value is ' +b ');
}
Say (' Joan blog ');
Execution results
A corresponding to the first argument " Jones blog ", B has no corresponding argument, so the value is undefined
Arguments objects
In fact, sometimes we do not specify the number of parameters when programming is more complex, are flexible use. There is an array of arguments in the function that stores the real parameter group, and by arguments we can know the number of arguments and the values.
function arg () {
var str = ' A total of ' +arguments.length+ ' arguments \ n ';
for (Var i=0;i<arguments.length;i++) {
str + = ' R ' + (i+1) + ' parameter value: ' +arguments[i]+ ' \ n ';
}
alert (str);
}
Arg (' Joan blog ', ' PHP blog ', ' Web Technology blog ');
Execution results
In the above example, we define the function arg without specifying a formal parameter for it, but instead use the arguments object to receive the argument, which is very flexible.
For example, we can use it to figure out the smallest number in a group of numbers, no matter how many. such as the following code:
function arg () {
var tmp = 0, str = ' in ';
for (Var i=0;i<arguments.length;i++) {for
(var g=0;g<arguments.length;g++) {
if (arguments[g]< Arguments[i]) {
tmp = Arguments[g];
}
}
STR + + arguments[i]+ ', ';
}
The smallest value in alert (STR.SUBSTR (0,str.length-1) + ' is ' +tmp ');
}
Arg (200,100,59,3500);
Perform 200,100,59,3500 four number comparison results
We're adding two numbers, 5 and 60, respectively.
function arg () {
var tmp = 0, str = ' in ';
for (Var i=0;i<arguments.length;i++) {for
(var g=0;g<arguments.length;g++) {
if (arguments[g]< Arguments[i]) {
tmp = Arguments[g];
}
}
STR + + arguments[i]+ ', ';
}
The smallest value in alert (STR.SUBSTR (0,str.length-1) + ' is ' +tmp ');
}
Arg (200,100,59,3500,5,60);
Perform 200,100,59,3500,5,60 six number comparison results
Based on the results of two operations, we find that no matter how many numbers we pass in, we can compare the results correctly. Arguments generally used in the number of arguments, such as the above example, you can pass 5 numbers in the comparison, you can also pass 100 numbers to compare all can.
The above JS function arguments array to obtain the actual number of parameters to achieve the implementation of small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.