【问题标题】:Converting an array to a function arguments list [duplicate]将数组转换为函数参数列表 [重复]
【发布时间】:2010-11-21 22:18:20
【问题描述】:

是否可以将 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);
  }
}

【问题讨论】:

标签: javascript arrays arguments


【解决方案1】:

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

app[func]( ...args );

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

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

在 MDN 上阅读这些方法:

【讨论】:

  • window 似乎没有必要。
  • 如果你想在一个对象中调用一个函数,这不起作用——例如以下不起作用:window.document.execCommand.apply(window,["insertHorizontalRule",false])
  • 那是因为,在您的情况下,您应该指定window.document 作为第一个参数,而不仅仅是windowwindow.document.execCommand.apply(window.document, ... )
  • window 实际上在 NodeJS 等非浏览器 JavaScript 框架中毫无意义,因此我建议将其从答案中删除。
  • 如果你可以使用 ES6 特性,你甚至可以使用f(...[1,2,3])
【解决方案2】:

另一个类似主题的帖子中的一个非常易读的示例:

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

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

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

还有here a link to the original post,我个人很喜欢它的可读性

【讨论】:

  • 如果可行,为什么不可行? document.body.setAttribute.apply( this, ["foo", "bar"] ); 我需要将可变参数发送到具有不同参数要求的各种对象方法。 快速编辑:显然this 必须是 document.body 或任何父级
  • 在 Typescript 构造函数上,这将引发错误:Only a void function can be called with the 'new' keyword
【解决方案3】:
app[func].apply(this, args);

【讨论】:

    【解决方案4】:

    您可能想查看在 Stack Overflow 上发布的 similar question。它使用.apply() 方法来完成此操作。

    【讨论】:

      【解决方案5】:

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

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

      但与以下相比,这似乎需要大量工作和混淆:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-02
        • 1970-01-01
        • 1970-01-01
        • 2022-07-07
        • 2023-03-13
        • 2019-01-21
        • 2014-07-14
        相关资源
        最近更新 更多