问题描述
在JavaScript中,反引号似乎与单引号相同。例如,我可以使用反引号来定义这样的字符串:
In JavaScript, a backtick seems to work the same as a single quote. For instance, I can use a backtick to define a string like this:
var s = `abc`;
有什么方法可以使反引号的行为与单引号的行为有所不同?
Is there any way in which the behavior of the backtick actually differs from that of a single quote?
推荐答案
这是一个名为。
This is a feature called template literals.
它们在ECMAScript 2015规范的先前版本中被称为模板字符串。
They were called "template strings" in prior editions of the ECMAScript 2015 specification.
Firefox 34,Chrome 41和Edge 12及更高版本支持模板文字,但是不是通过互联网资源管理器。
Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.
- 示例:
- 官方规格:(有点干)
- Examples: http://tc39wiki.calculist.org/es6/template-strings/
- Official specification: ECMAScript 2015 Language Specification, 12.2.9 Template Literal Lexical Components (a bit dry)
模板文字可用于表示多行字符串和可以使用插值来插入变量:
Template literals can be used to represent multi-line strings and may use "interpolation" to insert variables:
var a = 123, str = `---
a is: ${a}
---`;
console.log(str);
输出:
---
a is: 123
---
更重要的是,它们不仅可以包含变量名称,还可以包含任何Javascript表达式:
What is more important, they can contain not just a variable name, but any Javascript expression:
var a = 3, b = 3.1415;
console.log(`PI is nearly ${Math.max(a, b)}`);
这篇关于在JavaScript中使用反引号字符(`)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!