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' ,字符串模板可以识别代码中的换行。