JS and PHP in the function of a bit different, php-shaped participation in the number of arguments to match, and JS flexible, can be arbitrarily transmitted parameters, the actual parameter is less than formal parameters or more will not error.
More arguments than parameters do not error
?
1 2 3) 4 5 |
function say(a){ alert(a); } say( ‘琼台博客‘ , ‘WEB技术博客‘ ); |
Execution results
Let's take a look at the results of more formal parameters than arguments.
?
1 2 3) 4 5 |
function say(a,b){ alert( ‘a 的值是 ‘ +a+ ‘\nb 的值是 ‘ +b); } say( ‘琼台博客‘ ); |
Execution results
A corresponds to the first argument " Qiong Tai Blog ", B has no corresponding argument so the value is undefined
Arguments Object
In fact, sometimes we do not specify the number of parameters when the programming is more complex, are flexible use. In the function there is an array arguments is a special storage of real parameter groups, through the arguments we can know the number of arguments and values.
?
1 2 3 4 5 6 7 8 |
function arg(){
var str =
‘总共传了‘
+arguments.length+
‘个参数\n‘
;
for
(
var i=0;i<arguments.length;i++){
str +=
‘第‘
+(i+1)+
‘个参数值:‘
+arguments[i]+
‘\n‘
;
}
alert(str); } arg(
‘琼台博客‘
,
‘PHP博客‘
,
‘WEB技术博客‘
);
|
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 calculate the smallest number in a set of numbers, regardless of the number of numbers. such as the following code:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function arg(){
var tmp = 0, str =
‘在 ‘
;
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)+
‘ 里最小的值是 ‘
+tmp); } arg(200,100,59,3500);
|
Perform 200,100,59,3500 four number comparison results
We're adding two numbers, 5 and 60, respectively.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function arg(){
var tmp = 0, str =
‘在 ‘
;
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)+
‘ 里最小的值是 ‘
+tmp); } arg(200,100,59,3500,5,60);
|
Perform 200,100,59,3500,5,60 six number comparison results
Based on the results of the two operations, we find that no matter how many numbers we pass in, we can compare the results correctly. Arguments generally used in the variable number of arguments, such as the above example, you can pass 5 numbers into the comparison, you can also pass 100 numbers in the comparison can be.
JS function arguments array to get the actual number of arguments passed