-2

Possible Duplicate:
Pass arbitrary number of parameters into Javascript function

How can the following be achieved with n arguments?

function aFunction() {

    if ( arguments.length == 1 ) {
        anotherFunction( arguments[0] );
    } else if ( arguments.length == 2 ) {
        anotherFunction( arguments[0], arguments[1] );
    } else if ( arguments.length == 3 ) {
        anotherFunction( arguments[0], arguments[1], arguments[2] );
    }

}

function anotherFunction() {
    // got the correct number of arguments
}
Community
  • 1
  • 1
sq2
  • 575
  • 4
  • 11

5 Answers5

2

You don't need to do this. Here is how you can call it without caring how many arguments you have:

function aFunction() {
    anotherFunction.apply(this, arguments);
}

function anotherFunction() {
    // got the correct number of arguments
}
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100
0

You can use the .apply() method to call a function providing arguments as an array or array-like object:

function aFunction() {
    anotherFunction.apply(this, arguments);
}

(If you check the MDN doco I linked to you'll see it mentions your specific example of passing all of a function's arguments to some other function, though obviously there are many other applications.)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

Use apply(). This method on the Function's prototype allows you to call a function with a specified this context, and pass the arguments as an array or an array-like object.

anotherFunction.apply(this, arguments);
alex
  • 479,566
  • 201
  • 878
  • 984
0

Like this:

function aFunction() {
    var args = Array.prototype.slice.call(arguments, 0);
    anotherFunction.apply(this, args);
}
Lucas Green
  • 3,951
  • 22
  • 27
0

Here is the Sample function...

functionName = function() {
   alert(arguments.length);//Arguments length.           
}
Sandy
  • 6,285
  • 15
  • 65
  • 93