注:本文为 《 JavaScript 完全手册(2018版) 》第15节,你可以查看该手册的完整目录。
现在我们来看看 JavaScript 中允许使用的引号及其独特的特性。
JavaScript允许您使用3种类型的引号:
- 单引号(
'
) - 双引号(
"
) - 反引号 (
`
)
前 2 个基本相同:
const test = 'test' const bike = "bike"
使用这 2 种方法几乎没有差别。唯一的区别在于必须转义用于分隔字符串的引号字符:
const test = 'test' const test = 'te\'st' const test = 'te"st' const test = "te\"st" const test = "te'st"
有各种风格指南,建议始终使用一种风格与另一种风格。
我个人更喜欢单引号,并且只在 HTML 中使用双引号。
反引号 (“) 是 JavaScript 的最新成员,因为它们在 2015 年 ES6 才推出。
它们具有独特的功能:它们允许多行字符串。
使用转义字符,常规字符串也可以转换为多行字符串:
const multilineString = 'A string\non multiple lines'
使用反引号,者可以避免使用转义字符:
const multilineString = `A string on multiple lines`
不仅如此。您可以使用 ${}
语法插入变量或表达式:
const multilineString = `A string on ${1+1} lines`
我们将在一篇单独的文章中介绍了反引号驱动的字符串,称为字面量模板(Template Literals),它更深入地介绍了更多细节。
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂