面试题答案
一键面试代码实现
function printMessage(message) {
console.log(message);
}
let name = 'John';
let age = 30;
let templateMessage = `Hello, my name is ${name} and I'm ${age} years old.`;
printMessage(templateMessage);
模板字符串优势
- 更简洁的字符串拼接:相较于普通字符串通过
+
运算符拼接变量,模板字符串使用${}
嵌入变量,语法更简洁直观,例如普通字符串拼接方式为'Hello, my name is'+ name +'and I\'m'+ age +'years old.'
,代码冗长且容易出错。 - 支持多行字符串:模板字符串可以直接换行书写多行文本,普通字符串则需要使用转义字符
\n
来模拟换行,如:
let multiLineTemplate = `This is the first line.
This is the second line.`;
let multiLineNormal = 'This is the first line.\nThis is the second line.';
模板字符串在处理多行文本时更易读。
性能影响
- 现代引擎优化:在现代 JavaScript 引擎(如 V8)中,模板字符串的性能与普通字符串拼接差异不大。引擎针对模板字符串进行了优化,使得其解析和执行效率有所提升。
- 复杂表达式情况:如果
${}
中包含复杂的表达式,每次使用模板字符串时都需要计算表达式的值,可能会带来一定性能开销。但如果表达式结果不变,提前计算好并使用普通字符串拼接可能性能更优。例如:
// 假设这是一个复杂计算函数
function complexCalculation() {
let sum = 0;
for (let i = 0; i < 1000000; i++) {
sum += i;
}
return sum;
}
// 模板字符串每次都计算
let templateWithComplex = `Result: ${complexCalculation()}`;
// 提前计算好,普通字符串拼接性能可能更好
let result = complexCalculation();
let normalWithPreCalculated = 'Result:'+ result;