2

I have a function which is like this (but with more parameters):

function do_something(n1, n2, n3){
    return((n1-n2)*n3);
}

And then I have an array which contains 3 items, and are the parameters of that function:

my_array = [10,123,14];

For example,

 do_something(my_array[0], my_array[1], my_array[2]);

The following is probably not valid code for JavaScript but I want something like this,

 do_something(for(var i = 0; i < my_array.length; i++){
                  add_parameter(my_array[i]);
              });

So, is there any efficient way to make the elements of the array the parameters of function?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Fahem Moz
  • 327
  • 3
  • 11

2 Answers2

5

Use spread syntax introduced in ES2015:

do_something(...my_array);

This will spread the elements of my_array as individual arguments to do_something. If my_array contains 10, 123, 14 it will be equivalent to calling do_something(10, 123, 14).

Of course, you can still use Function#apply if you want support for Internet Exploder for the ES5 version:

do_something.apply(null /* the this value */, my_array);

apply essentially does the same thing. It takes in an array of arguments and executes the given function with those arguments as individual arguments to the function (and this value).

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
4

Use Function.Prototype.apply:

do_something.apply(null, myArray);

or using ES2015/ES6 use spread as mentioned in the other answer

do_something(...myArray);

Dan D
  • 2,493
  • 15
  • 23