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 the 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.