在JavaScript字符串中扩展$ {var}引用 [英] Expanding ${var} references in a JavaScript string

查看:93
本文介绍了在JavaScript字符串中扩展$ {var}引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习普通JavaScript以外的东西和正在阅读的书,这会告诉我这样的说法:

Learning something beyond vanilla JavaScript and the book I'm reading is telling me a statement like:

let someVar = 'Happy';
console.log('I hope you have a ${someVar} day.');

应该显示快乐"吗?在日志或警报中,或者可能在任何地方.

Should display 'Happy'? in the log or an alert or possibly anywhere.

它不起作用.我使用的是FireFox Dev Ed,我只了解整个内容:

It doesn't work. I'm using FireFox Dev Ed and I just get a line with the entire:

${someVar}

在其中.任何指导...这是一个奇怪的翻译问题还是ES6 +问题?

in it. Any guidance... Is this a weird transpiler issue or ES6+ issue?

推荐答案

您需要在字符串周围加上反引号,以便解释器将其正确解释为模板文字.

You need backticks surrounding the string there in order for the interpreter to properly interpret it as a template literal.

let someVar = 'Happy';
console.log(`I hope you have a ${someVar} day.`);

当您使用普通字符串时,可以使用单引号'或双引号",但是在使用模板文字时,必须始终使用反引号`.

When you have a normal string, you can use single quotes ' or double quotes ", but when you're using a template literal, you must always use backticks `.

即使您没有内插任何变量,也可以使用反引号,例如,这样就不必转义引号字符.

You can also use backticks anyway even if you aren't interpolating any variables inside, just so you don't have to escape quote characters, for example.

这篇关于在JavaScript字符串中扩展$ {var}引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆