-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
  • 565
  • 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
  • 32,797
  • 13
  • 71
  • 95
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
  • 143,356
  • 28
  • 190
  • 232
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
  • 460,746
  • 196
  • 858
  • 974
0

Like this:

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

Here is the Sample function...

functionName = function() {
   alert(arguments.length);//Arguments length.           
}
Sandy
  • 6,122
  • 15
  • 66
  • 90