将数组转换为函数参数列表

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上阅读这些方法:

  • 如果你可以使用ES6功能,你甚至可以使用`f(... [1,2,3])`. (4认同)

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)

在这里一个链接到原来的职位,我个人很喜欢它的可读性


JJ *_*wax 12

您可能想看一下Stack Overflow上发布的类似问题.它使用该.apply()方法来实现此目的.