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);
}
}
This question is related to
javascript
arrays
arguments
@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")
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
app[func].apply(this, args);
You might want to take a look at a similar question posted on Stack Overflow. It uses the .apply()
method to accomplish this.
Source: Stackoverflow.com