Java Reference
In-Depth Information
some of the formal parameters can be named. In a bad sense, you can argue that you
need to validate the number of arguments passed to the function if you want the callers to
pass the same number of arguments as the number of declared formal parameters.
Inside every function body, an object reference named
arguments
is available. It acts
like an array, but it is an object, not an array. Its
length
property is the number of actual
arguments passed to the function. The actual arguments are stored in the
arguments
object using indexes 0, 1, 2, 3, and so on. The first argument is
arguments[0]
, the second
argument is
arguments[1]
, and so on. The following rules are applied for arguments for a
function call:
arguments
•
The passed arguments to the function are stored in the
object
•
If the number of passed arguments is less than the declared
formal parameters, the unfilled formal parameters are initialized
to
undefined
•
If the number of passed arguments is greater than the number
of formal parameters, you can access the additional arguments
using the
arguments
object. In fact, you can access all arguments
all the time using the
arguments
object
•
If an argument is passed for a formal parameter, the formal
parameter name and the
arguments
object indexed property for
that formal parameter are bound to the same value. Changing
the parameter value or the corresponding value in the
arguments
object changes both
Listing 4-5 shows the code for an
avg()
function that compute average of passed
arguments. The function does not declare any formal parameters. It checks that at least
two arguments are passed and all arguments must be numbers (primitive numbers or
Number objects).
Listing 4-5.
A Function Using the arguments Object to Access All Passed Arguments
// avg.js
function avg() {
// Make sure at least two arguments are passed
If (arguments.length < 2) {
throw new Error(
"Minimum 2 arguments are required to compute average.");
}
// Compute the sum of all arguments
var sum = 0;
for each (var arg in arguments) {
if (!(typeof arg === "number" ||
arg instanceof Number)) {
throw new Error("Not a number: " + arg);
}
Search WWH ::
Custom Search