【问题标题】:Spread operator ES5 equivalent扩展运算符 ES5 等效
【发布时间】:2021-08-18 22:02:15
【问题描述】:

下面是我尝试转换为 ES5 以兼容 IE 的代码。

$.when(...requests).then(function(...responses) {
   // More code goes here
}

到目前为止,我可以将其转换为以下内容并且效果很好,但我仍然无法替换 then 部分。

$.when.apply(null, requests).then(function(...responses) {
   // More code goes here
}

任何建议都将不胜感激。

【问题讨论】:

  • 为什么不转译代码?
  • 另外,您似乎只是在询问其他参数语法:function(...responses)。只有$.when(...requests) 使用传播。

标签: javascript jquery ecmascript-6


【解决方案1】:

arguments

$.when.apply(null, requests).then(function() {
   var responses = [].concat.apply([], arguments); // Get a standard array from arguments object
   // More code goes here
}

作为免责声明,我引用 MDN 关于 arguments 的使用:

如果您正在编写与 ES6 兼容的代码,那么应该首选使用 rest 参数。

所以当你没有 ES6 支持时(这似乎是你的情况),那么使用 arguments 就可以了,否则你应该在函数参数列表中使用扩展语法。

【讨论】:

  • 感谢您的回答,它似乎可以稍微调整一下 -> var responses = [].concat(arguments)[0];.
  • 确实如此。我在答案中更正了这一点。它实际上应该使用apply,否则无法转换为标准数组。但这种转换是可选的。如果不使用.forEach、...等Array方法,可以直接使用responses = arguments或直接使用arguments
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 2022-06-30
  • 1970-01-01
  • 2014-08-21
  • 2017-12-20
  • 2016-09-20
  • 2020-04-13
相关资源
最近更新 更多