How Can I Pass An Array's Elements As Individual Arguments To A Function?
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
Solution 1:
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).
Solution 2:
do_something.apply(null, myArray);
or using ES2015/ES6 use spread as mentioned in the other answer
do_something(...myArray)
;
Post a Comment for "How Can I Pass An Array's Elements As Individual Arguments To A Function?"