tags:

views:

47

answers:

2

How would I get this array to be passed in as a set of strings to the function? This code doesn't work, but I think it illustrates what I'm trying to do.

var strings = ['one','two','three'];

someFunction(strings.join("','")); // someFunction('one','two','three');

Thanks!

+5  A: 

Use apply().

var strings = ['one','two','three'];

someFunction.apply(null, strings); // someFunction('one','two','three');

If your function cares about object scope, pass what you'd want this to be set to as the first argument instead of null.

Amber
Also, `null` isn't a valid parameter for call or apply in ES5.
Eli Grey
+4  A: 

The solution is rather simple, each function in JavaScript has a method associated with it, called "apply", which takes the arguments you want to pass in as an array.

So:

var strings = ["one", "two", "three"];
someFunction.apply(this, strings);

The 'this' in the apply indicates the scope, if its just a function in the page without an object, then set it to null, otherwise, pass the scope that you want the method to have when calling it.

In turn, inside of the someFunction, you would write your code something like this:

function someFunction() {
  var args = arguments; // the stuff that was passed in
  for(var i = 0; i < args; ++i) {
    var argument = args[i];
  }
}
Michael
Note that just referencing |arguments| will slow down the execution of your JavaScript in most (all?) browsers.
sdwilsh
This is an example, not a performance tuning exercise.
Michael