Convert an array into a separate argument strings

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.


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

Tags:

Javascript