dpq*_*dpq 234 javascript arrays arguments
是否可以将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);
}
}
Run Code Online (Sandbox Code Playgroud)
shu*_*ter 289
是.在当前版本的JS中,您可以使用:
app[func]( ...args );
Run Code Online (Sandbox Code Playgroud)
ES5及更早版本的用户需要使用以下.apply()方法:
app[func].apply( this, args );
Run Code Online (Sandbox Code Playgroud)
在MDN上阅读这些方法:
Wil*_*ilt 119
var args = [ 'p0', 'p1', 'p2' ];
function call_me (param0, param1, param2 ) {
// ...
}
// Calling the function using the array with apply()
call_me.apply(this, args);
Run Code Online (Sandbox Code Playgroud)
而在这里一个链接到原来的职位,我个人很喜欢它的可读性