Ryan Florence
Ryan Florence

Reputation: 13483

Convert an array into a separate argument strings

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!

Upvotes: 29

Views: 18727

Answers (2)

Amber
Amber

Reputation: 526573

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.

Upvotes: 50

Michael
Michael

Reputation: 1706

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

Upvotes: 11

Related Questions