什么时候应该在JavaScript中使用双引号或单引号? [英] When should I use double or single quotes in JavaScript?
问题描述
console.log( double);
与 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.
推荐答案
在不同库中使用单号或双号的最可能原因是程序员的偏好和/或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'");
这可能会变得很复杂:
alert("It's \"game\" time.");
alert('It\'s "game" time.');
ECMAScript 6中的另一个新选项是模板文字,它们使用后退标记字符:
Another option, new in ECMAScript 6, is template literals which use the backtick character:
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
模板文字为以下内容提供了一种清晰的语法:变量插值,多行字符串等等。
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
请注意,正式指定了 JSON 以使用双引号,这可能值得考虑,具体取决于系统要求。
Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.
这篇关于什么时候应该在JavaScript中使用双引号或单引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!