开发者

In Javascript, is there a way to convert an object array to parameters on a function call?

开发者 https://www.devze.com 2023-01-28 05:08 出处:网络
Suppose I have an array such as: var arr = [1, 2, 3]; And I have a function: function f (x, y, z) { ... }

Suppose I have an array such as:

var arr = [1, 2, 3];

And I have a function:

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

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

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

But let's suppose I don't know t开发者_开发问答he length of the array until runtime. Is there a way to do this? Thanks!

Mike


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

f.apply(context, arr);

...where context will become the value of this within the call.

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


Use the Function object's apply method:

var args = [1,2,3];

f.apply(null, args)

apply takes two arguments, the first being the value of this within the function at invocation time, and the second being an array of arguments to pass to the function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号