是否可以将 JavaScript 中的数组转换为函数参数序列?示例:
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 中,您可以使用:
app[func]( ...args );
ES5 及更早版本的用户需要使用 .apply()
方法:
app[func].apply( this, args );
在 MDN 上阅读这些方法:
- .apply()
- spread "..." operator (不要与相关的 rest "..." parameters 运算符相混淆:最好阅读两者!)
关于javascript - 将数组转换为函数参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1316371/