字符串模板语法是一种方便插入变量和表达式的字符串拼接方式,它使用反引号()包裹字符串,并使用${}`来插入动态的内容。以下是一些字符串模板语法的例子和说明:
1.插入变量:
const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!
在${}内部可以插入变量,它会被解析为对应变量的值,并与其他静态字符串拼接在一起。
2.表达式求值:
const x = 10;
const y = 5;
const result = `The sum of ${x} and ${y} is ${x + y}.`;
console.log(result); // Output: The sum of 10 and 5 is 15.
在${}内部可以进行表达式求值,这里的${x + y}会被计算为表达式的结果并替换其中。
3.多行字符串:
const multiline = `
This is
a multiline
string.
`;
console.log(multiline);
/*
Output:
This is
a multiline
string.
*/
字符串模板语法允许创建多行字符串,只需在反引号的起始和结束位置进行换行操作即可。