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.
精彩评论