29

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!

2 Answers 2

50

ES6

For ES6 JavaScript you can use the special destructuring operator :

var strings = ['one', 'two', 'three'];
someFunction(...strings);

ES5 and olders

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, null isn't a valid parameter for call or apply in ES5.
Null is a valid argument for es5, and in es3 it is replaced by the global object. There may be some implementation differences but null is valid esdiscuss.org/topic/…
11

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];
  }
}

1 Comment

Note that just referencing |arguments| will slow down the execution of your JavaScript in most (all?) browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.