Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
If you can't edit the function signature or how x is declared, then I don't really see how you could change it into anything better – Karl Johan May 18 '10 at 9:59

3 Answers

up vote 36 down vote accepted

This does exactly what you want:

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

Read more about apply here

share|improve this answer
Thanx, that's what i wanted. – Robert May 18 '10 at 11:57

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);
share|improve this answer

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])
  }
}
share|improve this answer
6  
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 May 18 '10 at 11:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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