dpq dpq - 7 months ago 31
Javascript Question

Converting an array to a function arguments list

Is it possible to convert an array in JavaScript into a function argument sequence? Example:

run({ "render": [ 10, 20, 200, 200 ] });

function run(calls) {
var app = .... // app is retrieved from storage
for (func in calls) {
// What should happen in the next line?
var args = ....(calls[func]);
app[func](args); // This is equivalent to app.render(10, 20, 200, 200);


Yes. You'll want to use the .apply() method. For example:

app[func].apply( this, args );

EDIT - Original answer specified this||window as the first argument. In browsers, this resolves to window if called outside a method anyway, and window is also browser-specific, so let's get rid of it.