views:

75

answers:

3

Hi all,

i'd like to call a function using an array as a parameters:

var x = [ 'p0', 'p1', 'p2' ];
call_me ( x[0], x[1], x[2] ); // i don't like it

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

Is there a better way of passing the contents of x into call_me()?

Ps. I can't change the signature of call_me(), nor the way x is defined.

Thanks in advance

+7  A: 

This does exactly what you want:

var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);

Read more about apply here

KaptajnKold
Thanx, that's what i wanted.
Robert
A: 

Why dont you pass the entire array and process it as needed inside the function?

Like so:

var x = [ 'p0', 'p1', 'p2' ]; 
call_me(x)
function call_me(params){
  for(i=0;i<params.length;i++){
    alert(params[i])
  }
}
Charlie boy
It's because i can't modify call_me(). It is defined in some other library and it is not possible to mess with the API.
Robert
+2  A: 

Assuming that call_me is a global function, so you don't expect this to be set.

var x = ['p0', 'p1', 'p2'];
call_me.apply(null, x);
plexer