字符串模板是一种使用反引号(`)的字符串语法,可以在其中使用 ${} 对表达式求值,并将结果插入到字符串中。
例如:
const name = 'Alice';
const age = 18;
const message = `My name is ${name}, and I'm ${age} years old.`;
console.log(message);
输出结果为:
My name is Alice, and I'm 18 years old.
标记函数是一种使用函数来处理字符串模板的方式。在函数中,可以访问到模板字符串中的所有内容,并可以自行处理。
例如:
function myTag(strings, ...values) {
console.log(strings); // ["My name is ", ", and I'm ", " years old."]
console.log(values); // ["Alice", 18]
return `Hello, ${strings[0]}${values[0]}! You're ${values[1]} years old.`;
}
const name = 'Alice';
const age = 18;
const message = myTagMy name is ${name}, and I'm ${age} years old.
;
console.log(message);
输出结果为:
["My name is ", ", and I'm ", " years old."]
["Alice", 18]
Hello, My name is Alice! You're 18 years old.