Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
    
Check for a similar question also here: stackoverflow.com/questions/2856059/… –  Wilt Feb 25 '14 at 11:14

4 Answers 4

up vote 97 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
    
window does not seem to be necessary. –  JBCP Sep 24 '14 at 21:52
app[func].apply(this, args);
share|improve this answer

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

A very readable example from another post on similar topic:

var x = [ 'p0', 'p1', 'p2' ];

function call_me (param0, param1, param2 ) {
    // ...
}

// Calling the function using the array with apply()
call_me.apply(this, x);

And here a link to the original post that I personally liked for it's readability

share|improve this answer
    
This is not a good SO overflow answer because the details aren't included in the answer, but the link is a good one, and the linked to answer is easy to understand. –  JBCP Sep 24 '14 at 21:52
    
@JBCP I added the content to my answer. –  Wilt Sep 26 '14 at 6:58
1  
Thanks, much better! –  JBCP Sep 27 '14 at 20:28
    
If that works, why won't this work? document.body.setAttribute.apply( this, ["foo", "bar"] ); I need to send variable arguments to various object methods with different argument requirements. Quick edit: Apparently this has to be document.body, or whatever the parent is –  bryc Feb 25 at 6:17

Your Answer

 
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.