将ES6箭头函数转换为ES5

7

我在一个 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中运行尝试的版本时,会出现什么错误? - user5063151
脚本将会崩溃,在控制台中我会得到“无效字符”的提示。 - TonyT
2个回答

12
当你有 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+方法。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接