Converting an array to a function arguments list

dpq picture dpq · Aug 22, 2009 · Viewed 161.1k times · Source

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

Answer

shuckster picture shuckster · Aug 22, 2009

Yes. In current versions of JS you can use:

app[func]( ...args );

Users of ES5 and older will need to use the .apply() method:

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

Read up on these methods at MDN: