首页 > 解决方案 > Javascript字符串插值的使用方法

问题描述

我遇到了这个使用字符串插值的开发人员的例子。

他使用它的方式如下:

console.log(`Hello, $userName`); 

直到后来在他的示例中,我才发现这有什么问题。他再次进行了字符串插值,但这次不同。这次他使用了括号。像这样:

console.log(`The user asked ${question}`); 

有什么不同 ?我使用哪种方式有关系吗?还是仅仅是开发人员的错误。

标签: javascript

解决方案


最简单的方法是尝试

如您所见,第一个没有做任何事情

var $userName = "Mike", userName = "Michael", question = "What's up?"

console.log(`Hello, $userName`); // not a valid JS string interpolation

console.log(`The user asked ${question}`); // This one works

// Perhaps he meant

console.log(`Hello`, $userName); 

// or more likely

console.log(`Hello, ${userName}`);


推荐阅读