将 ES6 箭头函数转换为 ES5

Convert ES6 Arrow Function to ES5

提问人:TonyT 提问时间:3/23/2019 更新时间:3/23/2019 访问量:5856

问:

我找到了一个可以在我正在处理的 Leaflet 项目中使用的函数。该函数是 ES6 编写的,它在 Firefox 和 Chrome 中都运行良好。但是,我也需要以 IE 为目标。在我的研究中,我发现IE目前不接受ES6 Arrow功能。我还发现,如果将 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);
});
JavaScript ECMAScript-6 宣传册

评论

0赞 3/23/2019
你得到什么错误?当您在 IE 中运行尝试的版本时?
0赞 TonyT 3/23/2019
脚本将崩溃,在控制台中我得到无效字符。

答:

12赞 CertainPerformance 3/23/2019 #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);
});

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

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

0赞 Code4Art 3/23/2019 #2

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

所以,只需添加语句,它应该可以工作return

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