Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
182
rated 0 times [  185] [ 3]  / answers: 1 / hits: 17659  / 13 Years ago, sun, september 4, 2011, 12:00:00

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

More From » javascript

 Answers
31

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

[#90273] Friday, September 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
kevonmoisesf questions
Sat, Jan 23, 21, 00:00, 3 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
Wed, Jun 12, 19, 00:00, 5 Years ago
;