ECMAScript functions do not mind how many parameters are passed in, and errors will not occur due to inconsistent parameters. In fact, the function body can receive the parameters passed in through the arguments object.
function box() {
return arguments[0 ] ' | ' arguments[1]; //Get the value of each parameter
}
alert(box(1,2,3,4,5,6)); //Pass parameters
The length attribute of the arguments object can get the number of parameters.
function box() {
return arguments.length; //Get 6
}
alert(box(1,2,3,4,5,6));
We can use the length attribute to intelligently determine how many parameters there are, and then apply the parameters appropriately.
For example, you want to implement an addition operation to accumulate all the numbers passed in, but the number of numbers is uncertain.
function box() {
var sum = 0 ;
if (arguments.length == 0) return sum; //If there are no parameters, exit
for(var i = 0;i < arguments.length; i ) { //If there are, accumulate
sum = sum arguments[i];
}
return sum; //Return the cumulative result
}
alert(box(5,9,12));
The functions in ECMAScript do not have the function overloading function like other high-level languages.
function box(num) {
return num 100;
}
function box (num) { //This function will be executed
return num 200;
}
alert (box(50)); //return result