views:

1088

answers:

4

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);
  }
}
+3  A: 

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.

brownstone
+1  A: 
app[func].apply(this, args);
Eric Anderson
+3  A: 

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

jgeewax
A: 

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

Manimala
Did you even read the answers above? You need to execute callFunction.apply(this, arr).
David Parunakian