模板字符串为JavaScript提供了简单的字符串插值功能,从此以后,你可以通过一种更加美观、更加方便的方式向字符串中插值了。
描述:模板字符串是通过反引号(``)来创建字符串的,跟以往的单引号('')和双引号("")的创建方法是一样的。
const a = 'Hello, World!'; //单引号
const b = "Hello, World"; //双引号
const c = `Hello, World!`; //反引号
功能:模板字符串支持占位符(${expression})。占位符内的表达式在运行时进行计算,并将结果插入到字符串中。
占位符表达式:
1. 变量
const a = 'YES';
const b = `${a}`;
以上JS执行后,占位符${a}被替换成a里面的值,所以后面的b输出的内容也就是YES了.
2. 表达式
const a = 1;
const b = 2;
const c = `a + b = ${a + b}, a比b大?,${a > b ? '是' : '否'}`;
3. 函数
const t = 1;
function sum(a, b) {
return a + b;
}
const result = `计算两个数相加: ${sum(t, 2)}`;
数据类型的转换
占位符表达式结果都会被隐式转换为字符串输出。
例如number类型:
const n = 3.5;
const message = `The number is ${n}`;
message; // => `The number is 3.5`
数组类型:
const numbers = [1, 2, 3];
const message = `The numbers are ${numbers}`;
message; // => 'The numbers are 1,2,3'
如果占位符包含一个对象,按照转换为字符串的规则,该对象也被转换为字符串。调用对象的方法toString()来获取对象的字符串表示。
数组转换的原理是:数组方法join(',')在数组转换为字符串时执行。因此字符串插值结果为'The numbers are 1,2,3'。
转义占位符
因为占位符格式${expression}在模板文字中具有特殊含义,所以不能在`${someCharacters}`不转义的情况下使用字符序列。
也就是里面引用的内容必须是已经声明了的。
const message = `Some weird characters: ${abc}`;
// Throws "ReferenceError: abc is not defined"
如果想把‘${abc}‘当做字符串输出,可以使用转义符(反斜杠\)。
const message = `Some weird characters: \${abc}`;
message; // => 'Some weird characters follow: ${abc}'
也就是说如果你需要在模板字符串中引入字符$和{。无论你要实现什么样的目标,你都需要用反斜杠转义每一个字符:`\$`和`\{`。
const message = `Some weird characters: \${abc} \${abc \${`;
message; // => 'Some weird characters: ${abc} ${abc ${'