在 JavaScript 中,_模板字符串_可以在字符串里嵌入表达式,这也被称为字符串插值。
这项功能扩展了内置的 String 全局对象的能力。
在 JavaScript 中,只要把文本用反引号包起来,就能创建模板字符串。 它们不仅允许文本中包含换行和其他特殊字符,还可以嵌入变量和其他表达式。
const num1 = 1;
const num2 = 2;
`Adding ${num1} and ${num2} gives ${num1 + num2}.`;
// => Adding 1 and 2 gives 3.
在上面的例子中,反引号(``)用于表示模板字符串。${...}是用于替换的占位符。
任何非字符串类型都会被_隐式_转换为字符串。
这一主题在类型转换概念中有所介绍。
所有类型的表达式都可以用在模板字符串中。
const track = 'JavaScript';
`This track on exercism.org is ${track.toUpperCase()}.`;
// => This track on exercism.org is JAVASCRIPT.
当你需要把字符串排成多行时:
`This is an example of using template
strings to accomplish multiple
lines`;
借助可用的替换能力,你还可以在处理过程中引入逻辑,来决定输出的字符串应该是什么。
处理这种逻辑的一种方式是使用三元运算符。
它以略有不同的写法提供了相同的if/else条件功能。
要在模板字符串语法中实现逻辑:
const grade = 95;
`You have ${grade > 90 ? 'passed' : 'failed'} the exam.`;
// => You have passed the exam.