字符串模板补充

2020-03-06  本文已影响0人  静小弟

带标签的模板

let a = 1
let b = 2
function tag (strings, ...params) {
    console.log(strings) // 所有字符串的集合 [hello, '', world]
    console.log(params) // 所有转译内容的集合 [3, 2]
}
tag`hello ${a + b} world ${a * b}`
// tag([hello, '',world], 2,3)

在标签函数的第一个参数中,存在一个raw属性,可以访问原始字符串

function tag(strings) {
    console.log(strings.raw)
}
tag`string text line 1 \n string text line 2`;
// 打印出来的字符串是包含'\' 'n' 就是字符串没有被 \n 转译成换行 

官方文档

上一篇 下一篇

猜你喜欢

热点阅读