当我将它添加到我的字符串消息中时,使用插值 ${itemName} 没有改变颜色
我期待得到
的结果你桌的价格是80美元 但我在我的输出中得到了这个:你的 ${itemName} 的价格是 ${price} 美元
您的代码的问题是您使用单引号 (') 将字符串括在 messageToPrint2 中,但您需要使用反引号 (``) 进行插值才能在 JavaScript 中工作。此外,您应该使用 ${} 来括起变量,而不是 '${}'。
这里是更正后的代码:
//Concatenation and Interpolation
var price = 80;
var itemName = "table";
var messageToPrint = "the price for your "+itemName+" is "+price+" dollars"; //concatenation
let messageToPrint2 = `the price for your ${itemName} is ${price} dollars`; //interpolation
console.log(messageToPrint2);
你桌的价格是80美元。