在JavaScript中使用反引号字符(`)? [英] Usage of the backtick character (`) in JavaScript?

查看:2713
本文介绍了在JavaScript中使用反引号字符(`)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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?

†请注意,在程序员中,反引号是更常被称为严重重音的名称。程序员有时也会使用替代名称反引号和反向。另外,关于Stack Overflow 和其他地方,反击的其他常见拼写是后退和返回勾选。

† Note that among programmers, "backtick" is one name for what is more generally called the grave accent. Programmers also sometimes use the alternate names "backquote" and "backgrave". Also, on Stack Overflow and elsewhere, other common spellings for "backtick" are "back-tick" and "back tick".

推荐答案

这是一个名为 模板文字

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中使用反引号字符(`)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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