推荐答案
在模板字符串中使用表达式,可以通过 ${} 语法嵌入任意有效的 JavaScript 表达式。模板字符串使用反引号(`)包裹,表达式会被计算并转换为字符串,然后插入到模板字符串中。
const name = "Alice";
const age = 25;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // 输出: Hello, my name is Alice and I am 25 years old.本题详细解读
1. 模板字符串的基本语法
模板字符串是 ECMAScript 6(ES6)引入的一种新的字符串字面量语法,使用反引号(`)包裹。与普通字符串不同,模板字符串可以跨多行,并且支持嵌入表达式。
2. 表达式的嵌入
在模板字符串中,可以通过 ${} 语法嵌入任意有效的 JavaScript 表达式。表达式会被计算,并将结果转换为字符串,然后插入到模板字符串中。
const a = 10;
const b = 20;
const result = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(result); // 输出: The sum of 10 and 20 is 30.3. 表达式的灵活性
${} 中可以嵌入任何有效的 JavaScript 表达式,包括函数调用、三元运算符、对象属性访问等。
const user = {
name: "Bob",
age: 30
};
const greeting = `Hello, ${user.name}. You are ${user.age >= 18 ? "an adult" : "a minor"}.`;
console.log(greeting); // 输出: Hello, Bob. You are an adult.4. 多行字符串
模板字符串还支持多行字符串,无需使用 \n 或字符串拼接。
const multiLine = ` This is a multi-line string. It preserves the line breaks and indentation. `; console.log(multiLine);
5. 标签模板
模板字符串还可以与标签函数一起使用,标签函数可以对模板字符串的内容进行处理。
// www.javascriptcn.com code example
function highlight(strings, ...values) {
return strings.reduce((result, str, i) => {
return `${result}${str}<strong>${values[i] || ''}</strong>`;
}, '');
}
const name = "Charlie";
const age = 35;
const highlighted = highlight`Hello, my name is ${name} and I am ${age} years old.`;
console.log(highlighted); // 输出: Hello, my name is <strong>Charlie</strong> and I am <strong>35</strong> years old.通过以上示例,可以看出模板字符串在嵌入表达式时的灵活性和强大功能。