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

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

问题描述

在JavaScript中,反引号的作用似乎与单引号相同。例如,我可以使用反引号定义这样的字符串:

  var s =`abc`; 

反引号的行为实际上与单引号的行为有区别吗? / p>




†请注意,在程序员中,反引号是通常被称为重音符号的一个名称。程序员有时还会使用备用名称反引号和反引号。另外,关于堆栈溢出和其他地方, backtick的其他常见拼写是 back-tick和 back勾选。

解决方案

这是一个称为 模板文字



它们在ECMAScript 2015规范的先前版本中称为模板字符串。



Firefox,34,Chrome 41和Edge 12及更高版本支持模板文字,但是





模板文字可以用来表示多行字符串,并且可以使用插值以插入变量:

  var a = 123,str =`--- 
a是:$ { a}
---`;
console.log(str);

输出:

 -
a是:123
---

更重要的是,它们不仅可以包含变量名,还可以包含任何JavaScript表达式:

  var a = 3,b = 3.1415; 

console.log(`PI接近$ {Math.max(a,b)}`);


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 a way in which the behavior of the backtick actually differs from that of a single quote?


† 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.

They were called "template strings" in prior editions of the ECMAScript 2015 specification.

Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.

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);

Output:

---
   a is: 123
---

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天全站免登陆