将ES6箭头功能转换为ES5

时间:2019-03-22 23:55:37

标签: javascript ecmascript-6 leaflet

我找到了可以在我正在工作的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);
});

2 个答案:

答案 0 :(得分:10)

当您具有要与ES5兼容的ES6 +代码时,要转译语法,您可以使用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);
});

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

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

答案 1 :(得分:0)

  

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

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

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

相关问题