Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array of values:

['a', 'b', 'c', 'd']

and I need to pass these as parameters to a function:

window.myFunction('a', 'b', 'c', 'd');

This would be easier if I could just pass the array/object into the function, but the functions are written by other people or already exist and I cannot change them - they need to be passed as individual parameters, which is what I need solved.

The number of values being passed is not consistent. It may be one, it may be 100.

Again, I cannot affect the functions. They are how they are, and I will always receive an array of values to pass into them.

Thanks

share|improve this question
1  
"The number of values being passed is not consistent". What about the number of arguments expected by the function? Are they known? –  Sébastien Oct 24 '13 at 15:53
 
Nope, neither are known. –  Randy Hall Oct 24 '13 at 16:23
add comment

2 Answers

up vote 6 down vote accepted

Use the .apply method of the Function object.

window.myFunction.apply(window, ['a','b','c','d']);

The .apply method invokes the function you're calling, but lets you set the function's this value (the first argument) and lets you set its arguments using an Array (the second argument).

So here we kept window as the this value, and we're passing the Array as the individual arguments. The Array members will be distributed as though they were passed as individual arguments, so it's as if you had done this:

window.myFunction('a','b','c','d');
share|improve this answer
 
It says you posted at the same time, but I'm selecting yours for explanation. Thanks much! –  Randy Hall Oct 24 '13 at 16:23
add comment

Try

window.myFunction.apply(window, ['a', 'b', 'c', 'd']);
share|improve this answer
add comment

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.