views:

225

answers:

2

In javascript if I have some function I can use the arguments object to look at how many parameters were passed in. Is there a way to call a second function and pass those arguments as if they are just normal separate parameters?

something like this:

function f()
{
g(arguments);
}

function g(a, b, c)
{
alert(a+b+c);
}

So in this case if I called f(1,2,3) I would get an alert of 6. Just to be clear, I'm not trying to pass a variable number of arguments, just a way to pass the arguments object as normal separate parameters to other functions (possibly native javascript functions)

+8  A: 
function f() 
{
    g.apply(this,arguments);
}

see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/apply for more details on this technique

also, note that the first parameter defines the context in which the function will run. passing null for the first argument will simply use the global context (window).

Jonathan Fingland
A: 

Another way would be using the evil eval();

I don't recommend this though.

function f()
{
    var eval_string = "g(";
    for(var i=0; i<arguments.length; i++)
        eval_string += arguments[i] + ", ";  // if arguments[i] is an integer

    eval_string += ");"

    eval(eval_string);
}
Luca Matteis
Terrible for so many reasons
Triptych
you are terrible!
Luca Matteis