将数组转换为函数参数列表 [英] Converting an array to a function arguments list
本文介绍了将数组转换为函数参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将 JavaScript 中的数组转换为函数参数序列?示例:
Is it possible to convert an array in JavaScript 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);
}
}
推荐答案
是的.在当前版本的 JS 中,您可以使用:
Yes. In current versions of JS you can use:
app[func]( ...args );
ES5 及更早版本的用户将需要使用 .apply()
方法:
Users of ES5 and older will need to use the .apply()
method:
app[func].apply( this, args );
在 MDN 上阅读这些方法:
Read up on these methods at MDN:
- .apply()
- 传播..." 运算符(不要与相关的rest "..." parameters 操作符:这两个都很好阅读!)
- .apply()
- spread "..." operator (not to be confused with the related rest "..." parameters operator: it's good to read up on both!)
这篇关于将数组转换为函数参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文