【ES6系列】Template

ES5 中字符串換行、包含變量或表達式、包含邏輯運算怎麼處理?ES6有更優雅便捷的方式嗎?

ES6之前用字符串拼接+邏輯判斷的方式進行處理。

ES6 新增語法:

1、字符串拼接 String Literals

const a = 10
const b = 11
const c = 'javascript'
const str = `my age is ${a+b} i like ${c}`
console.log(str) // my age is 21 i like javascript

2、tag 函數 Tag Literals

//定義一個 Tag 函數,然後用這個 Tag 函數來充當一個模板引擎:

// 參數:strings 返回模板客串中被所有變量分隔開的字符串集合
// type 參數對應模板字符串中的第一個變量,Tag 函數可以有多個 type 類似的參數
function Price(strings, type) {
  let s1 = strings[0]
  const retailPrice = 20
  const wholeSalePrice = 16
  let showTxt
  if (type === 'retail') {
    showTxt = '購買單價是:' + retailPrice
  } else {
    showTxt = '購買進價是:' + wholeSalePrice
  }
  return `${s1}${showTxt}`
}
let showTxt = Price `您此次的${'retail'}`
console.log(showTxt) //您此次的購買單價是:20

3、字符串換行

ES6 字符串換行不再需要手動添加 '\n' ,字符串模板可以識別代碼中的換行。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章