22-模板字符串中的表达式
5.12 模板字符串中的表达式
模板字符串在第3章中已经介绍过,它可以将任意表达式的值注入到字符串中。第3章中的例子是用模板字符串表示当前温度。如果要表示温差,或者要表示华氏温度而非摄氏度,应该怎么做呢?可以在模板字符串中使用表达式:
const roomTempC = 21.5;
let currentTempC = 19.5;
const message = 'The current temperature is' +
'${currentTempC-roomTempC}\u00b0C different than room temperature.';
const fahrenheit =
'The current temperature is ${currentTempC * 9/5 + 32}\u00b0F';
这里又一次看到了表达式所带来的优美对称性。由于变量本身就是一种简单的表达式,所以可以在模板字符串中使用变量。