我发现了一个可以在我正在工作的 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);
});
最佳答案
当您有 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
回调中返回
L.marker...
。
请注意,这只会转译语法,而不是方法 - 如果您使用的是 ES6+ 方法(例如,Array.prototype.includes
),Babel 不会够了——您需要手动更改代码以使用 ES5 方法(如 indexOf
),或者更好的选择是包含一个 polyfill (example) 以在客户端上定义 ES6+ 方法查看您的页面。
关于javascript - 将 ES6 箭头函数转换为 ES5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55309225/