模版字面量

69 阅读1分钟
  • 使用起来非常方便不需要使用转义符,`` ${}为占位符里面可以是js表达式
const name = '派派'
const age = 18
const string = `你好我是${name}我今年${age}岁`
  • 标签模版
const name = '派派'
const age = 18
const tag = (arr, ...placeholder) => {
    console.log(arr) //['你好我是', '我今年'] 非占位字符,这里数组的长度永远比占位符的个数大一
    console.log(...placeholder) // ‘派派’ 18 占位字符
    arr.reduce((prev,cur,i) => {
        prev + `<span class="color">${placeholder[i-1]}</span>` + cur
    })
}
const result = tag`你好我是${name}我今年${age}岁`
console.log(result)