javascript javascript中`和'之间的区别(如果有的话)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33679732/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:47:46  来源:igfitidea点击:

Difference (if there is any) between ` and ' in javascript

javascriptapostrophe

提问by roscioli

Recently ran into some JS code that uses ` and '. I can't figure out if there is a different use for each apostrophe. Is there any?

最近遇到一些使用`和'的JS代码。我不知道每个撇号是否有不同的用途。有没有?

回答by Alex Wayne

' or " denote a stringand ` denotes a template string. Template strings have some abilities that normal strings do not. Most importantly, you get interpolation:

' 或 " 表示一个字符串,` 表示一个模板字符串。模板字符串有一些普通字符串没有的能力。最重要的是,你得到了插值:

var value = 123;
console.log('test ${value}') //=> test ${value}
console.log(`test ${value}`) //=> test 123

And multiline strings:

和多行字符串:

console.log('test
test')
// Syntax error

console.log(`test
test`)
// test
// test

They have some other tricks too, more on template strings here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

他们也有一些其他技巧,更多关于模板字符串在这里:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

Note they are not supported in all javascript engines at the moment. Which is why template strings are often used with a transpiler like Babel.which converts the code to something that will work in any JS interpreter.

请注意,目前并非所有 javascript 引擎都支持它们。这就是为什么模板字符串经常与像Babel这样的转译器一起使用的原因它将代码转换为可以在任何 JS 解释器中工作的东西。