Is it possible to convert an array 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);
  }
}
share|improve this question

3 Answers

up vote 37 down vote accepted

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

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

EDIT - Actually, my ||window bit is superfluous, since this resolves to window when called outside of a function anyway.

share|improve this answer
This is straight up G. – Alan Jan 28 at 23:40

You might want to take a look at a similar question posted on Stack Overflow. It uses the .apply() method to accomplish this.

share|improve this answer
app[func].apply(this, args);
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.