使用 visual studio 代码的 javascript 插值不起作用

问题描述 投票:0回答:1

enter image description here

enter image description here

当我将它添加到我的字符串消息中时,使用插值 ${itemName} 没有改变颜色

我期待得到

的结果

你桌的价格是80美元 但我在我的输出中得到了这个:你的 ${itemName} 的价格是 ${price} 美元

javascript visual-studio-code interpolation
1个回答
1
投票

您的代码的问题是您使用单引号 (') 将字符串括在 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美元。

© www.soinside.com 2019 - 2024. All rights reserved.