开发者

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

开发者 https://www.devze.com 2023-04-02 03:28 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Is it possible to send a variable number of arguments to a JavaScript function?
This question already has answers here: Closed 11 years ago.

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 wi开发者_运维问答thout 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]); }


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']);


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


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');  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号