javascript ES2015 Babel String Interpolation 不适用于撇号(但适用于双引号)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31000691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES2015 Babel String Interpolation not working with apostrophe (but does with double quotes)
提问by HockeyJ
I am using babel / grunt to learn some ES2015.
我正在使用 babel / grunt 来学习一些 ES2015。
According to this postthere is no real difference in Javascript between single and double quotes. i.e. 'test' and "test".
根据这篇文章,单引号和双引号之间的 Javascript 没有真正的区别。即“测试”和“测试”。
When trying string interpolation though, it seems there is an issue with babeljs (or more likely - me). What is wrong with the code below please?
但是,在尝试字符串插值时,babeljs(或者更有可能 - 我)似乎存在问题。请问下面的代码有什么问题?
According to this document, it seems both should work. There are no errors in the Chrome console.
根据这个文件,似乎两者都应该工作。Chrome 控制台中没有错误。
Working Js:
工作JS:
var name = "Bob", time = "today";
alert(`Hello ${name}, how are you ${time}?`);
Transpiles to:
转译为:
var name = "Bob",
time = "today";
alert("Hello " + name + ", how are you " + time + "?");
Provides the expected result.
提供预期的结果。
Failing Js:
失败的JS:
var forename = 'bob', surname = 'test';
alert('hello ${forename} ${surname} - how are you?');
Transpiles to:
转译为:
var forename = "bob",
surname = "test";
alert("hello ${forename} ${surname} - how are you?");
and provides the following output:
并提供以下输出:
回答by CodingIntrigue
You're right, there is no different between '
and "
when it comes to strings, but in order to do string interpolation, you mustuse backticks around your template string, e.g.:
你说得对,之间不存在不同'
而"
当它涉及到的字符串,而是为了做串插,你必须使用你的周围模板字符串,如反引号:
ES2015
ES2015
var forename = 'bob', surname = 'test';
alert(`hello ${forename} ${surname} - how are you?`);
Resulting ES5
结果 ES5
var forename = 'bob',
surname = 'test';
alert('hello ' + forename + ' ' + surname + ' - how are you?');