Saturday, March 17, 2007

Using the arguments Array

[Deprecated]The arguments of a function are maintained in an array. Within a function, you can address the arguments passed to it as follows:
arguments[i]

where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

Using the arguments array, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then treat each argument using the arguments array.

For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

function myConcat(separator) {
var result="" // initialize list
// iterate through arguments
for (var i=1; i < arguments.length; i++) {
result += arguments[i] + separator
}
return result
}

You can pass any number of arguments to this function, and it creates a list using each argument as an item in the list.

// returns "red, orange, blue, "
myConcat(", ","red","orange","blue")

// returns "elephant; giraffe; lion; cheetah; "
myConcat("; ","elephant","giraffe","lion", "cheetah")

// returns "sage. basil. oregano. pepper. parsley. "
myConcat(". ","sage","basil","oregano", "pepper", "parsley")

See the Function object in the Core JavaScript Reference for more information.

JavaScript 1.3 and earlier versions. The arguments array is a property of the Function object and can be preceded by the function name, as follows:

functionName.arguments[i]

No comments :