何时在JavaScript中使用双引号或单引号? [英] When to use double or single quotes in JavaScript?
问题描述
console.log(double);
vs console.log('single');
在处理字符串时,我看到越来越多的JavaScript库使用单引号。使用其中一个的原因是什么?我认为它们几乎可以互换。
I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other? I thought they're pretty much interchangeable.
推荐答案
在不同的库中使用single vs double的最可能的原因是程序员偏好和/或API一致性。
The most likely reason for use of single vs double in different libraries is programmer preference and/or API consistency.
除了保持一致外,请使用最适合字符串的:。
Other than being consistent, use whichever best suits the string:.
使用另一种类型的引用作为文字:
Using the other type of quote as a literal:
alert('Say "Hello"');
alert("Say 'Hello'");
...但这可能变得复杂......
…but this can get complicated…
alert("It's \"game\" time.");
alert('It\'s "game" time.');
ES6中的新选项模板文字,使用反向标记
字符:
Another option, new in ES6, are Template literals which use the back-tick
character:
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character in a string`);
模板文字提供了一个干净的语法:变量插值,多行字符串等。
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
这篇关于何时在JavaScript中使用双引号或单引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!