22
votes

Possible Duplicate:
Is it possible to send a variable number of arguments to a JavaScript function?

I can use arguments to get a variable number of arguments within a function, but how can I pass them to another function without knowing its prototype?

function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f) { f(arguments); } // not correct, what to do?
run(show, 'foo', 'bar');

Note: I cannot guarantee the number of arguments needed for the function f that is passed to run. Meaning, even though the example shown has 2 arguments, it could be 0-infinite, so the following isn't appropriate:

function run(f) { f(arguments[1], arguments[2]); }
4
I disagree, as you can see, show has defined arguments, it does not use arguments. I have already tried apply that way with no luck.steveo225
Well, as you have noticed by now, apply is the only way to do this, therefore it is a duplicate.Felix Kling
Yes, except the way arguments used was entirely different and ultimately the point of the question.steveo225

4 Answers

30
votes

The main way to pass a programmatically generated set of arguments to a function is by using the function's 'apply' method.

function show(foo, bar) {
  window.alert(foo+' '+bar);
}
function run(f) {
  // use splice to get all the arguments after 'f'
  var args = Array.prototype.splice.call(arguments, 1);
  f.apply(null, args);
}

run(show, 'foo', 'bar');
6
votes

You can in fact do this with apply, if I understand your question correctly:

function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f, args) { f.apply(null,args); } 
run(show, ['foo', 'bar']);
2
votes

you need to use the apply function.. here is how u do it:

function variableFunction1()  
    {  

   alert("variableFunction1 arguments length: " + arguments.length);  

   // calls second varargs function keeping current 'this'.  
   variableFunction2.apply(this, arguments);  
}  

function variableFunction2()  
{  

   alert("variableFunction2 arguments length: " + arguments.length);  
}  

variableFunction1('a','b','c');  

Demo

0
votes

In your example to pass variable arguments to show this works

function show(foo, bar) { window.alert(foo+' '+bar); }
function run(f) { f.apply(null, Array().slice.call(arguments, 1)); }
run(show, 'foo', 'bar');