Converting an array to a function arguments list

JavascriptArraysArguments

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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:

Solution 2 - Javascript

A very readable example from another post on similar topic:

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

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

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

And here a link to the original post that I personally liked for its readability

Solution 3 - Javascript

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

Solution 4 - Javascript

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

Solution 5 - Javascript

@bryc - yes, you could do it like this:

Element.prototype.setAttribute.apply(document.body,["foo","bar"])

But that seems like a lot of work and obfuscation compared to:

document.body.setAttribute("foo","bar")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondpqView Question on Stackoverflow
Solution 1 - JavascriptshucksterView Answer on Stackoverflow
Solution 2 - JavascriptWiltView Answer on Stackoverflow
Solution 3 - JavascriptEric AndersonView Answer on Stackoverflow
Solution 4 - JavascriptJJ GeewaxView Answer on Stackoverflow
Solution 5 - Javascriptuser1527225View Answer on Stackoverflow