學習ES6非常棒的特性-字元串常量基礎
字元串常量基礎
在ES2015之前我們是這麼拼接字元串的:
var result = 10;var prefix = "the first double digit number I learnt was ";var assembled = prefix + result.toString();console.log(assembled); // logs => the first double digit number I learnt was 10
在ES2015我們可以這麼做:
var result = 10;var assembled = `the first double digit number I learnt was ${result}`;console.log(assembled); // logs => the first double digit number I learnt was 10
通過 ${}引用外部的變數
字元串常量拼接裡面遍歷
假設我們有一個數組,我們怎麼遍歷它:
var data = [ // Data here];// loop through the datadata.forEach((datarecord, idx) => { // for each record we call out to a function to create the template let markup = createSeries(datarecord, idx); // We make a div to contain the resultant string let container = document.createElement("div"); container.classList.add("as-Series"); // We make the contents of the container be the result of the function container.innerHTML = markup; // Append the created markup to the DOM document.body.appendChild(container);});function createSeries(datarecord, idx) { return ` <div class="a-Series_Title">${datarecord.Title}</div> `;}
完整的拼接方法類似這樣:
function createSeries(datarecord, idx) { return ` <h2 class="a-Series_Title">${datarecord.Title}</h2> <p class="a-Series_Description"> <span class="a-Series_DescriptionHeader">Description: </span>${datarecord.Description} </p> <div class="a-EpisodeBlock"> <h4 class="a-EpisodeBlock_Title">First episodes</h4> </div> `;}
如果數據裡面又有一個數組,怎麼遍歷?
function createSeries(datarecord, idx) { return ` <h2 class="a-Series_Title">${datarecord.Title}</h2> <p class="a-Series_Description"> <span class="a-Series_DescriptionHeader">Description: </span>${datarecord.Description} </p> <div class="a-EpisodeBlock"> <h4 class="a-EpisodeBlock_Title">First episodes</h4> ${datarecord.Episodes.map((episode, index) => `<div class="a-EpisodeBlock_Episode"> <b class="">${index+1}</b> <span class="">${episode}</span> </div> ` )} </div>`};
ok. 然後列印出來:
Episodes1 Homecoming,2 New Colossus,3 Champion,4 Away,5 Paradise,6 Forking Paths,7 Empire of Light,8 Invisible Self
多了一個默認的逗號,怎麼辦。
${datarecord.Episodes.map((episode, index) => `<div class="a-EpisodeBlock_Episode"> <b class="">${index+1}</b> <span class="">${episode}</span> </div> `).join("")}
通過join方法處理一下就好了。
字元串常量裡面用if/else
${datarecord.Ended === true ? `` : `<div class="a-Series_More">More to come!</div>`}
使用返回另外一個值的函數
假設我們有這樣一個函數
const add = (a, b) => a + b;function getRatingsAverage(ratings) { return ratings.reduce(add) / ratings.length;}
這樣使用就可以了:
`<div class="a-UserRating">Average user rating: <b class="a-UserRating_Score">${getRatingsAverage(datarecord.UserRatings)}</b></div>`
安全
看一個例子:
var username = craig<script>alert("XSS")</ + script>;document.write(`<p>Hi ${username}</p>`);
用戶輸入了一個js代碼,然後我們直接填充到了username裡面。這個時候會導致瀏覽器彈出一個alert。 這樣肯定是不行的。
一般我們需要escape方法轉義一下,或者用textContent。
// HTML Escape helper utilityvar util = (function () { // Thanks to Andrea Giammarchi var reEscape = /[&<>"]/g, reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g, oEscape = { &: &, <: <, >: >, "": ', ": " }, oUnescape = { &: &, &: &, <: <, <: <, >: >, >: >, ': "", ': "", ": ", ": " }, fnEscape = function (m) { return oEscape[m]; }, fnUnescape = function (m) { return oUnescape[m]; }, replace = String.prototype.replace ; return (Object.freeze || Object)({ escape: function escape(s) { return replace.call(s, reEscape, fnEscape); }, unescape: function unescape(s) { return replace.call(s, reUnescape, fnUnescape); } });}());// Tagged template functionfunction html(pieces) { var result = pieces[0]; var substitutions = [].slice.call(arguments, 1); for (var i = 0; i < substitutions.length; ++i) { result += util.escape(substitutions[i]) + pieces[i + 1]; } return result;}var username = "Domenic Denicola";var tag = "& is a fun tag";console.log(html`<b>${username} says</b>: "${tag}"`);
以上就是今天的內容,感謝閱讀。
更多內容,點擊閱讀原文:
HTML templating with vanilla JavaScript ES2015 Template Literals
推薦閱讀:
※利用css畫出一個三角形
※十年web前端開發工程師告訴你怎樣零基礎入門
※TCP/IP網路模型
※html中的div標籤的含義和應用
※《Oli-Zhao的前端一萬小時》之:離不開的Git和GitHub(1)——版本控制、Git、GitHub初認識