模板字符串中变量需用 ${} 包裹,反引号定义;支持属性访问、方法调用、表达式(如三元、算术),但不可含语句;嵌套直接使用反引号;null/undefined 会转为对应字符串,可用 ?? 提供默认值。
${} 包住变量名就行模板字符串用反引号 ` 定义,变量必须写在 ${} 里面,不能只写 $var 或 ${var} 外面漏掉反引号——那根本不是模板字符串。
常见错误:把单引号或双引号当模板字符串用,比如 'Hello ${name}',这时 ${name} 就是纯文本,不会解析。
const name = 'Alice'; console.log(`Hello ${name}`); → 输出 Hello Alice
const user = { age: 30 }; console.log(`Age: ${user.age}`); → 支持点语法取属性const items = ['a', 'b']; console.log(`Count: ${items.length}`); → 支持方法调用和属性访问${} 里面不是只能写变量,任何能返回值的表达式都行,比如三元运算、函数调用、甚至简单算术。但注意:不能有语句(如 if、for、let),也不能有未声明的变量引用。
const x = 5; console.log(`Result: ${x > 3 ? 'big' : 'small'}`);console.log(`Uppercase: ${'hello'.toUpperCase()}
`);console.log(`Sum: ${2 + 3 * 4}`);${let y = 1}(let 是声明语句,非法)${console.log('hi')}(虽然语法合法,但副作用容易被忽略,不推荐)模板字符串支持嵌套,只要外层用反引号,内层也用反引号即可,不用像普通字符串那样拼接或转义。
const theme = 'dark'; const html = `${theme === 'dark' ? `Night mode` : `Day mode`}
Settings:
`;${`theme=${theme}`}
注意:嵌套时仍要确保每个 ${} 内部是完整表达式;如果逻辑复杂,建议先赋值给变量再插入,避免可读性崩坏。
"undefined"
如果变量是 null 或 undefined,${null} 会变成字符串 "null",${undefined} 变成 "undefined",不是空字符串。
${value ?? ''}
${user.name ?? 'Anonymous'}
0、false)?小心,${user.count || 'N/A'} 会让 0 也被替换成 'N/A'
真正容易被忽略的是:模板字符串本身不会做类型转换或容错,它只是字符串插值——值是什么,就转成什么字符串,连 Symbol 都会报 TypeError,除非显式调用 .toString()。