Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable number of arguments from one function to another [duplicate]

Tags:

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]); } 
like image 431
steveo225 Avatar asked Sep 04 '11 17:09

steveo225


People also ask

How many arguments can pass through a function?

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.

Can we pass a variable argument list to a function at runtime?

Every actual argument list must be known at compile time. In that sense it is not truly a variable argument list.


2 Answers

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'); 
like image 189
loganfsmyth Avatar answered Sep 27 '22 21:09

loganfsmyth


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']); 
like image 29
spike Avatar answered Sep 27 '22 19:09

spike