将数组转换为函数参数列表 [英] 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上阅读这两种方法:。apply(), spread...operator
Read up on both methods at MDN: .apply(), spread "..." operator
这篇关于将数组转换为函数参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文