up vote 2 down vote favorite
2

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

4 Answers

up vote 3 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.

link|flag
up vote 3 down vote

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

link|flag
up vote 1 down vote
app[func].apply(this, args);
link|flag
up vote -1 down vote

I want to pass the arry into function..as a parameter. ok. My code is function test{ var arr = new Array(3); arr[0] = "one"; arr[1]= "two"; callFunction(arr); //passing the array }

But it won't work? Can u help me?........... Thanks For Advance

link|flag
Did you even read the answers above? You need to execute callFunction.apply(this, arr). – David Parunakian Nov 5 '09 at 19:30

Your Answer

get an OpenID
or
never shown

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