簡體   English   中英

將 ES6 箭頭函數轉換為 ES5

[英]Convert ES6 Arrow Function to ES5

我找到了一個可以在我正在工作的 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回調中return L.marker...

請注意,這僅轉換語法,而不是方法 - 如果您使用 ES6+ 方法(例如, Array.prototype.includes ),Babel 是不夠的 - 您要么需要手動更改代碼以使用 ES5 方法(如indexOf ),或者更好的選擇,包括一個 polyfill( example )來在查看您頁面的客戶端上定義 ES6+ 方法。

如果箭頭函數只是返回單行代碼,則可以省略語句括號和 return 關鍵字。 這告訴箭頭函數返回語句。

所以,只需添加return語句,它應該可以工作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM