模板字符串
| 功能 | 普通字符串("…") | 模板字符串(…) |
|---|---|---|
| 变量插值 | ❌ 不支持 | ✅ 支持 ${} |
| 表达式嵌入 | ❌ | ✅ |
| 多行 | ❌ 需 \n | ✅ 直接回车 |
| 书写 HTML/SQL 等 | 一般 | ✅ 非常方便 |
普通使用方法
const age = 18
const height = 1.88
console.log('my age is ' + age + ' height is ' + height)
console.log('my father age is ' + age * 2 + ' eight is ' + (Number(height) + Number(0.1)))
//my age is 18 height is 1.88
//my father age is 36 eight is 1.98
console.log(`my age is ${age} height is ${height}`)
console.log(`my father age is ${age * 2} height is ${height + 0.1}`)
//my age is 18 height is 1.88
//my father age is 36 height is 1.98
在模板字符串中使用函数
const age = 18
const height = 1.88
function firstName () {
return 'why'
}
console.log('my name is ' + firstName())
console.log(`my name is ${firstName()}`)
//my name is why
//my name is why
、
其他的使用方法基本不用,可自己再网上找
标签模板字符串
function foo() {
console.log( '------')
}
foo()
foo``
//------
//------
第一个参数依然是模板字符串中整个字符串,只是被切割成了多块,放到了一个数组中 第二个参数是模板字符串中的第一个:${}。往后依次类推
function foo(m, n) {
console.log(m, n, "------");
}
const name = "why";
const age = 18;
foo('hello', 'world');
foo`hello${name}wo${age}rld`;