简体   繁体   English

在Javascript中,有没有办法将对象数组转换为函数调用的参数?

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

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: 是的,您可以使用'apply'javascript方法:

f.apply(context, arr);

...where context will become the value of this within the call. ...其中context将成为价值this通话中。

Some info here: http://www.webreference.com/js/column26/apply.html 这里有一些信息: http//www.webreference.com/js/column26/apply.html

Use the Function object's apply method: 使用Function对象的apply方法:

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. apply接受两个参数,第一个是调用时函数内的this值,第二个是传递给函数的参数数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM