转换一个JavaScript数组给函数的参数列表 [英] Converting a Javascript array to a function arguments list
本文介绍了转换一个JavaScript数组给函数的参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有可能一个数组转换成一个函数的参数顺序?例如:
运行({渲染:[10,20,200,200]});功能运行(呼叫){
VAR应用= .... //应用程序从存储检索
对(在调用FUNC){
//下一行应该发生什么?
变参= ....(电话[FUNC]);
应用[FUNC](参数); //这相当于app.render(10,20,200,200);
}
}
解决方案
是的。您将要使用。适用()
方法。例如:
应用[FUNC]。适用(这一点,参数);
编辑 - 指定此||窗口
作为第一个参数原来的答复。在浏览器中,这个
解析为窗口
如果调用的方法之外,无论如何,和窗口
也是特定浏览器,所以让我们摆脱它。
Is it possible to convert an array into a function argument sequence? Example:
run({ "render": [ 10, 20, 200, 200 ] });
function run(calls) {
var app = .... // app is retrieved from storage
for (func in calls) {
// What should happen in the next line?
var args = ....(calls[func]);
app[func](args); // This is equivalent to app.render(10, 20, 200, 200);
}
}
解决方案
Yes. You'll want to use the .apply()
method. For example:
app[func].apply( this, args );
EDIT - Original answer specified this||window
as the first argument. In browsers, this
resolves to window
if called outside a method anyway, and window
is also browser-specific, so let's get rid of it.
这篇关于转换一个JavaScript数组给函数的参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文