In Javascript, is there a way to convert an array of objects into function call parameters?

Suppose I have an array, for example:

var arr = [1, 2, 3];

And I have a function:

function f (x, y, z) { ... }

I want to call a function with a given array, where each index of the array is a parameter passed to the function. I could do this:

f(arr[0], arr[1], arr[2]);

But let me not know the length of the array until runtime. Is there any way to do this? Thank!

Mike

+3
source share
2 answers

Yes, you can use the "apply" javascript method:

f.apply(context, arr);

... where contextwill become the value thisinside the call.

Information here: http://www.webreference.com/js/column26/apply.html

+3
source

Function object apply:

var args = [1,2,3];

f.apply(null, args)

apply , this , - .

+2

Source: https://habr.com/ru/post/1778574/


All Articles