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]); }
Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.
Every actual argument list must be known at compile time. In that sense it is not truly a variable argument list.
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');
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']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With