【问题标题】:Convert ES6 Arrow Function to ES5将 ES6 箭头函数转换为 ES5
【发布时间】:2019-03-22 23:55:37
【问题描述】:

我找到了一个可以在我正在工作的 Leaflet 项目中使用的函数。该函数是用 ES6 编写的,它在 Firefox 和 Chrome 中都运行良好。但是,我也需要针对 IE。在我的研究中,我发现 IE 目前不接受 ES6 箭头功能。我还发现如果将 ES6 函数转换为 ES5,该函数将在 IE 中运行。几天来,我试图将以下函数转换为 ES5,但没有成功。我尝试的一些解决方案在这里发布。有人可以看看我的脚本,让我知道我做错了什么。另外,无论如何,ES6 有什么好处?更短的脚本?提前谢谢你。

这是有效的 ES6 脚本:

points.map((p, i) => L.marker(p).bindPopup(`marker${'<strong>' + pointData[i].cityName + '</strong>' + ', ' + '</br>'  + pointData[i].discrip +  "<br /><a class='fancybox-thumb' ' style='width:150px;' rel='fancybox-button'  rel='fancybox-thumb'   data-fancybox-group='"+ pointData[i].popup +"'   title='" + pointData[i].discrip + " '  href='graphic/"+ pointData[i].popup + "' ><img src='graphic/" + pointData[i].popup + "' alt='Image' ' style='width:150px;' ></a>" + "<br/><a href='http://www.google.com'  target='_blank'>Cedellion Report</a>"}`))
.forEach(function(marker) {
    map.addLayer(marker);
    oms.addMarker(marker);
});

这是我最好的尝试/猜测,没有任何乐趣。

points.map(function(p, i) {
L.marker(p).bindPopup(`marker${'<strong>' + pointData[i].cityName + '</strong>' + ', ' + '</br>'  + pointData[i].discrip +  "<br /><a class='fancybox-thumb' ' style='width:150px;' rel='fancybox-button'  rel='fancybox-thumb'   data-fancybox-group='"+ pointData[i].popup +"'   title='" + pointData[i].discrip + " '  href='graphic/"+ pointData[i].popup + "' ><img src='graphic/" + pointData[i].popup + "' alt='Image' ' style='width:150px;' ></a>" + "<br/><a href='http://www.google.com'  target='_blank'>Cedellion Report</a>"}`)})
.forEach(function(marker) {
map.addLayer(marker);
oms.addMarker(marker);
});

【问题讨论】:

  • 您遇到什么错误?当您在 IE 中运行您尝试的版本时?
  • 脚本将崩溃,在控制台中我得到 Invalid character。

标签: javascript ecmascript-6 leaflet


【解决方案1】:

当您有 ES6+ 代码想要兼容 ES5 时,要转译 语法,您可以使用像 Babel 这样的转译器自动完成。插入您的代码会得到以下结果:

points.map(function (p, i) {
  return L.marker(p).bindPopup("marker" + ('<strong>' + pointData[i].cityName + '</strong>' + ', ' + '</br>' + pointData[i].discrip + "<br /><a class='fancybox-thumb' ' style='width:150px;' rel='fancybox-button'  rel='fancybox-thumb'   data-fancybox-group='" + pointData[i].popup + "'   title='" + pointData[i].discrip + " '  href='graphic/" + pointData[i].popup + "' ><img src='graphic/" + pointData[i].popup + "' alt='Image' ' style='width:150px;' ></a>" + "<br/><a href='http://www.google.com'  target='_blank'>Cedellion Report</a>"));
}).forEach(function (marker) {
  map.addLayer(marker);
  oms.addMarker(marker);
});

您还需要转译模板文字 - 声明字符串并使用 + 连接而不是使用 ${} 语法。另外,你需要从.map回调中returnL.marker...

请注意,这只会转译语法,而不转译方法 - 如果您使用 ES6+ 方法(例如,Array.prototype.includes),Babel 是不够的 - 您要么需要更改手动代码以使用 ES5 方法(如 indexOf),或者更好的选择,包括 polyfill (example) 以在查看您页面的客户端上定义 ES6+ 方法。

【讨论】:

    【解决方案2】:

    如果一个箭头函数只是返回一行代码,你 可以省略语句括号和 return 关键字。这告诉 箭头函数返回语句。

    所以,只需添加 return 语句就可以了

    更多信息: https://codeburst.io/javascript-understand-arrow-function-syntax-ab4081bba85b

    【讨论】: