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

272

在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);
  }
}

3
请在此处检查是否有类似的问题:https://dev59.com/AXE85IYBdhLWcg3wShaf - Wilt
4
我猜这并不重要,但是把这个较旧的问题标记为新的被引用的问题的重复似乎有点奇怪? - shuckster
5个回答

335

是的,在当前版本的JS中,您可以使用:

app[func]( ...args );

使用ES5及更早版本的用户需要使用.apply()方法:

app[func].apply( this, args );

在MDN上了解这些方法:


窗口似乎不是必需的。 - JBCP
如果你想在对象内调用一个函数,以下方法不起作用:window.document.execCommand.apply(window,["insertHorizontalRule",false]) - adib
这是因为在你的情况下,你应该将window.document作为第一个参数指定,而不仅仅是windowwindow.document.execCommand.apply(window.document, ... ) - shuckster
1
“window” 在非浏览器 JavaScript 框架(如 NodeJS)中没有意义,因此我建议从答案中将其删除。 - zbr
4
如果您能使用ES6特性,甚至可以使用f(...[1,2,3]) - manixx
另一个好主意。完成了! - shuckster

126

一个来自类似话题的另一篇帖子中非常易读的例子:

var args = [ 'p0', 'p1', 'p2' ];

function call_me (param0, param1, param2 ) {
    // ...
}

// Calling the function using the array with apply()
call_me.apply(this, args);

这是我个人很喜欢的一篇文章,原帖链接在这里


如果那个可以运行,为什么这个不能运行呢?document.body.setAttribute.apply(this, ["foo", "bar"]); 我需要将可变参数发送到具有不同参数要求的各种对象方法中。_快速编辑:显然 this 必须是 document.body,或者是父级元素_。 - bryc
在Typescript构造函数中,这将引发错误:只有void函数可以使用'new'关键字调用 - Augie Gardner

25
app[func].apply(this, args);

12

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


1
"

@bryc - 是的,你可以这样做:

"
Element.prototype.setAttribute.apply(document.body,["foo","bar"])

但相比于以下方式,这似乎是很多工作和混淆:

document.body.setAttribute("foo","bar")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接