JS and PHP are a bit different from function parameters. The number of PHP-shaped participants should match, while JS is much more flexible and can pass parameters at will. There will be no errors compared to the actual parameters with fewer or more formal parameters.
There will be no errors in real reference and formal parameters
function says(a){alert(a); }say('Qiongtai Blog','WEB Technology Blog');Execution results
Let's take a look at the results of more formal references and real parameters
function says(a,b){alert('a's value is '+a+'/nb's value is '+b); }say('Qiongtai Blog');Execution results
a corresponds to the first actual parameter "Qiongtai Blog", b does not have a corresponding actual parameter so the value is undefined
arguments object
In fact, sometimes when the programming is more complicated, we do not specify the number of parameters, and we use them flexibly. There is an array argument in the function that specifically stores real parameter groups. Through arguments, we can know the number of real parameters and values.
function arg(){var str = 'A total of '+arguments.length+' parameters were passed '+arguments.length+'; for(var i=0;i<arguments.length;i++){ str += '+(i+1)+' parameter values: '+arguments[i]+'/n'; }alert(str);}arg('Qiongtai Blog','PHP Blog','WEB Technology Blog');Execution results
In the above example, we define the function arg and do not specify formal parameters for it, but use the arguments object to receive actual parameters, which is very flexible.
For example, we can use it to calculate the smallest number in a set of numbers, no matter how many of the numbers there are. As in 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]+',';}alert(str.substr(0,str.length-1)+' The smallest value is '+tmp);}arg(200,100,59,3500);Execute 200, 100, 59, 3500 Four numbers comparison results
We are adding two numbers, 5 and 60
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]+',';}alert(str.substr(0,str.length-1)+' The smallest value is '+tmp);}arg(200,100,59,3500,5,60);Execute 200, 100, 59, 3500, 5, 60 Six numbers comparison results
Based on the results of the two operations, we found that no matter how many numbers we pass, we can compare the results correctly. arguments are generally used in places where the actual parameters are uncertain. For example, in the example above, you can pass 5 numbers to compare, or you can pass 100 numbers to compare.