简体   繁体   English

JavaScript 中的双引号和单引号可以互换吗?

[英]Are double and single quotes interchangeable in JavaScript?

Consider the following two alternatives:考虑以下两种选择:

  • console.log("double");
  • console.log('single');

The former uses double quotes around the string, whereas the latter uses single quotes around the string.前者在字符串周围使用双引号,而后者在字符串周围使用单引号。

I see more and more JavaScript libraries out there using single quotes when handling strings.我看到越来越多的 JavaScript 库在处理字符串时使用单引号。

Are these two usages interchangeable?这两种用法可以互换吗? If not, is there an advantage in using one over the other?如果不是,使用一个比另一个有优势吗?

The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency.在不同的库中使用 single 和 double 的最可能原因是程序员偏好和/或 API 一致性。 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'");

This can get complicated:这可能会变得复杂:

alert("It's \"game\" time.");
alert('It\'s "game" time.');

Another option, new in ECMAScript 6, is template literals which use the backtick character: ECMAScript 6 中的另一个新选项是使用反引号字符的模板文字

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.模板文字提供了一种简洁的语法:变量插值、多行字符串等。

Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.请注意, JSON被正式指定为使用双引号,这可能值得考虑,具体取决于系统要求。

If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted.如果您正在处理 JSON,需要注意的是,严格来说,JSON 字符串必须是双引号。 Sure, many libraries support single quotes as well, but I had great problems in one of my projects before realizing that single quoting a string is in fact not according to JSON standards.当然,许多库也支持单引号,但在我意识到单引号字符串实际上不符合 JSON 标准之前,我在我的一个项目中遇到了很大的问题。

There is no one better solution ;没有更好的解决方案 however, I would like to argue that double quotes may be more desirable at times:但是,我想争辩说,有时双引号可能更可取:

  • Newcomers will already be familiar with double quotes from their language .新人已经熟悉他们语言中的双引号 In English, we must use double quotes " to identify a passage of quoted text. If we were to use a single quote ' , the reader may misinterpret it as a contraction. The other meaning of a passage of text surrounded by the ' indicates the 'colloquial' meaning. It makes sense to stay consistent with pre-existing languages, and this may likely ease the learning and interpretation of code.在英语中,我们必须使用双引号"来标识引用文本的段落。如果我们使用单引号' ,读者可能会将其误解为收缩。被'包围的文本段落的另一个含义表示'口语'的意思。与预先存在的语言保持一致是有意义的,这可能会简化代码的学习和解释。
  • Double quotes eliminate the need to escape apostrophes (as in contractions).双引号消除了转义撇号的需要(如在收缩中)。 Consider the string: "I'm going to the mall" , vs. the otherwise escaped version: 'I\\'m going to the mall' .考虑字符串: "I'm going to the mall" ,与其他转义版本: 'I\\'m going to the mall'
  • Double quotes mean a string in many other languages .双引号在许多其他语言中表示字符串 When you learn a new language like Java or C, double quotes are always used.当您学习 Java 或 C 等新语言时,总是使用双引号。 In Ruby, PHP and Perl, single-quoted strings imply no backslash escapes while double quotes support them.在 Ruby、PHP 和 Perl 中,单引号字符串表示没有反斜杠转义,而双引号支持它们。

  • JSON notation is written with double quotes. JSON 表示法是用双引号写的。

Nonetheless, as others have stated, it is most important to remain consistent.尽管如此,正如其他人所说,最重要的是保持一致。

Section 7.8.4 of the specification describes literal string notation. 规范的第 7.8.4 节描述了文字字符串表示法。 The only difference is that DoubleStringCharacter is "SourceCharacter but not double-quote" and SingleStringCharacter is "SourceCharacter but not single-quote".唯一的区别是 DoubleStringCharacter 是“SourceCharacter 但不是双引号”,而 SingleStringCharacter 是“SourceCharacter 但不是单引号”。 So the only difference can be demonstrated thusly:所以唯一的区别可以这样证明:

'A string that\'s single quoted'

"A string that's double quoted"

So it depends on how much quote escaping you want to do.所以这取决于你想要做多少引号转义。 Obviously the same applies to double quotes in double quoted strings.显然,这同样适用于双引号字符串中的双引号。

Single Quotes单引号

I wish double quotes were the standard, because they make a little bit more sense , but I keep using single quotes because they dominate the scene.我希望双引号是标准的,因为它们更有意义,但我一直使用单引号,因为它们在场景中占主导地位。

Single quotes:单引号:

No preference:没有偏好:

Double quotes:双引号:

I'd like to say the difference is purely stylistic, but I'm really having my doubts.我想说差异纯粹是风格上的,但我真的很怀疑。 Consider the following example:考虑以下示例:

/*
    Add trim() functionality to JavaScript...
      1. By extending the String prototype
      2. By creating a 'stand-alone' function
    This is just to demonstrate results are the same in both cases.
*/

// Extend the String prototype with a trim() method
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
};

// 'Stand-alone' trim() function
function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
};

document.writeln(String.prototype.trim);
document.writeln(trim);

In Safari, Chrome, Opera, and Internet Explorer (tested in Internet Explorer 7 and Internet Explorer 8 ), this will return the following:在 Safari、Chrome、Opera 和 Internet Explorer(在Internet Explorer 7Internet Explorer 8 中测试)中,这将返回以下内容:

function () {
    return this.replace(/^\s+|\s+$/g, '');
}
function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

However, Firefox will yield a slightly different result:但是,Firefox 会产生稍微不同的结果:

function () {
    return this.replace(/^\s+|\s+$/g, "");
}
function trim(str) {
    return str.replace(/^\s+|\s+$/g, "");
}

The single quotes have been replaced by double quotes.单引号已替换为双引号。 (Also note how the indenting space was replaced by four spaces.) This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes. (还要注意缩进空格是如何被四个空格替换的。)这给人的印象是至少有一个浏览器在内部解析 JavaScript,就好像所有内容都是用双引号编写的一样。 One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.有人可能会认为,如果一切都已经按照这个“标准”编写,那么 Firefox 解析 JavaScript 所需的时间就会更少。

Which, by the way, makes me a very sad panda, since I think single quotes look much nicer in code.顺便说一句,这让我很伤心,因为我认为单引号在代码中看起来更好。 Plus, in other programming languages, they're usually faster to use than double quotes, so it would only make sense if the same applied to JavaScript.另外,在其他编程语言中,它们的使用速度通常比双引号快,因此只有将其应用于 JavaScript 才有意义。

Conclusion: I think we need to do more research on this.结论:我认为我们需要对此做更多的研究。

This might explain Peter-Paul Koch's test results from back in 2003.这或许可以解释Peter-Paul Koch早在 2003 年的测试结果

It seems that single quotes are sometimes faster in Explorer Windows (roughly 1/3 of my tests did show a faster response time), but if Mozilla shows a difference at all, it handles double quotes slightly faster.似乎单引号有时在资源管理器 Windows 中更快(我的测试中大约 1/3 确实显示了更快的响应时间),但是如果 Mozilla 显示出完全不同,它处理双引号的速度会稍微快一些。 I found no difference at all in Opera.我在 Opera 中根本没有发现任何区别。

2014: Modern versions of Firefox/Spidermonkey don't do this anymore. 2014 年:现代版本的 Firefox/Spidermonkey 不再这样做了。

If you're doing inline JavaScript (arguably a "bad" thing, but avoiding that discussion) single quotes are your only option for string literals, I believe.我相信,如果您正在执行内联 JavaScript(可以说是一件“坏事”,但要避免讨论),引号是字符串文字的唯一选择。

Eg, this works fine:例如,这很好用:

<a onclick="alert('hi');">hi</a>

But you can't wrap the "hi" in double quotes, via any escaping method I'm aware of.但是您不能通过我知道的任何转义方法将“hi”括在双引号中。 Even &quot;甚至&quot; which would have been my best guess (since you're escaping quotes in an attribute value of HTML) doesn't work for me in Firefox.这本来是我最好的猜测(因为你在 HTML 的属性值中转义引号)在 Firefox 中对我不起作用。 " won't work either because at this point you're escaping for HTML, not JavaScript. "也不起作用,因为此时您要转义 HTML,而不是 JavaScript。

So, if the name of the game is consistency, and you're going to do some inline JavaScript in parts of your application, I think single quotes are the winner.因此,如果游戏的名称是一致性,并且您将在应用程序的某些部分执行一些内联​​ JavaScript,我认为单引号是赢家。 Someone please correct me if I'm wrong though.如果我错了,请有人纠正我。

Technically there's no difference.技术上没有区别。 It's only matter of style and convention.这只是风格和惯例的问题。

Douglas Crockford recommends using single quotes for internal strings and double quotes for external (by external we mean those to be displayed to user of application, like messages or alerts). Douglas Crockford建议对内部字符串使用单引号,对外部字符串使用双引号(外部我们指的是向应用程序用户显示的内容,如消息或警报)。

I personally follow that.我个人遵循这一点。

UPDATE: It appears that Mr. Crockford changed his mind and now recommends using double quotes throughout :)更新:似乎 Crockford 先生 改变了主意,现在建议在整个过程中使用双引号 :)

Strictly speaking, there is no difference in meaning;严格来说,意义没有区别; so the choice comes down to convenience.所以选择归结为方便。

Here are several factors that could influence your choice:以下是可能影响您选择的几个因素:

  • House style: Some groups of developers already use one convention or the other. House 风格:一些开发人员组已经使用了一种约定或另一种约定。
  • Client-side requirements: Will you be using quotes within the strings?客户端要求:您会在字符串中使用引号吗? (See Ady's answer .) (见阿迪的回答。)
  • Server-side language: VB.NET people might choose to use single quotes for JavaScript so that the scripts can be built server-side (VB.NET uses double-quotes for strings, so the JavaScript strings are easy to distinguished if they use single quotes).服务器端语言:VB.NET 的人可能会选择 JavaScript 使用单引号,这样脚本就可以在服务器端构建(VB.NET 对字符串使用双引号,因此如果使用单引号,JavaScript 字符串很容易区分)引号)。
  • Library code: If you're using a library that uses a particular style, you might consider using the same style yourself.库代码:如果您使用的是使用特定样式的库,您可以考虑自己使用相同的样式。
  • Personal preference: You might think one or other style looks better.个人偏好:您可能认为一种或其他风格更好看。

Let's look what a reference does.让我们看看引用的作用。

Inside jquery.js, every string is double-quoted.在 jquery.js 中,每个字符串都是双引号的。

So, beginning now, I'll use double-quoted strings.所以,从现在开始,我将使用双引号字符串。 (I was using single!) (我用的是单身!)

Just keep consistency in what you use.只需保持所用内容的一致性即可。 But don't let down your comfort level.但不要降低您的舒适度。

"This is my string."; // :-|
"I'm invincible."; // Comfortable :)
'You can\'t beat me.'; // Uncomfortable :(
'Oh! Yes. I can "beat" you.'; // Comfortable :)
"Do you really think, you can \"beat\" me?"; // Uncomfortable :(
"You're my guest. I can \"beat\" you."; // Sometimes, you've to :P
'You\'re my guest too. I can "beat" you too.'; // Sometimes, you've to :P

ECMAScript 6 update ECMAScript 6 更新

Using template literal syntax .使用模板文字语法

`Be "my" guest. You're in complete freedom.`; // Most comfort :D

I hope I am not adding something obvious, but I have been struggling with Django , Ajax , and JSON on this.我希望我没有添加明显的东西,但我一直在与DjangoAjax和 JSON 苦苦挣扎。

Assuming that in your HTML code you do use double quotes, as normally should be, I highly suggest to use single quotes for the rest in JavaScript.假设在您的 HTML 代码中确实使用了双引号(通常应该如此),我强烈建议在 JavaScript 中对其余部分使用单引号。

So I agree with ady , but with some care.所以我同意ady ,但要小心。

My bottom line is:我的底线是:

In JavaScript it probably doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles.在 JavaScript 中,这可能无关紧要,但是一旦您将其嵌入 HTML 或类似内容中,您就会开始遇到麻烦。 You should know what is actually escaping, reading, passing your string.你应该知道什么是真正的转义、阅读、传递你的字符串。

My simple case was:我的简单案例是:

tbox.innerHTML = tbox.innerHTML + '<div class="thisbox_des" style="width:210px;" onmouseout="clear()"><a href="/this/thislist/'
                   + myThis[i].pk +'"><img src="/site_media/'
                   + myThis[i].fields.thumbnail +'" height="80" width="80" style="float:left;" onmouseover="showThis('
                   + myThis[i].fields.left +','
                   + myThis[i].fields.right +',\''
                   + myThis[i].fields.title +'\')"></a><p style="float:left;width:130px;height:80px;"><b>'
                   + myThis[i].fields.title +'</b> '
                   + myThis[i].fields.description +'</p></div>'

You can spot the ' in the third field of showThis.您可以在 showThis 的第三个字段中找到 '。

The double quote didn't work!双引号不起作用!

It is clear why, but it is also clear why we should stick to single quotes... I guess...原因很清楚,但也很清楚为什么我们应该坚持使用单引号......我猜......

This case is a very simple HTML embedding, and the error was generated by a simple copy/paste from a 'double quoted' JavaScript code.这种情况是一个非常简单的 HTML 嵌入,错误是通过从“双引号”JavaScript 代码中简单复制/粘贴生成的。

So to answer the question:所以要回答这个问题:

Try to use single quotes while within HTML.尝试在 HTML 中使用单引号。 It might save a couple of debug issues...它可能会节省一些调试问题......

It's mostly a matter of style and preference.这主要是风格和偏好的问题。 There are some rather interesting and useful technical explorations in the other answers, so perhaps the only thing I might add is to offer a little worldly advice.在其他答案中有一些相当有趣和有用的技术探索,所以也许我唯一可以补充的就是提供一些世俗的建议。

  • If you're coding in a company or team, then it's probably a good idea to follow the "house style".如果您在公司或团队中编码,那么遵循“家庭风格”可能是个好主意。

  • If you're alone hacking a few side projects, then look at a few prominent leaders in the community.如果你一个人在做一些业余项目,那么看看社区中的一些杰出领导者。 For example, let's say you getting into Node.js .例如,假设您进入Node.js Take a look at core modules, for example, Underscore.js or express and see what convention they use, and consider following that.看看核心模块,例如Underscore.js或 express,看看它们使用什么约定,并考虑遵循它。

  • If both conventions are equally used, then defer to your personal preference.如果这两种约定都被同等使用,那么请遵循您的个人喜好。

  • If you don't have any personal preference, then flip a coin.如果你没有任何个人偏好,那就抛硬币吧。

  • If you don't have a coin, then beer is on me ;)如果你没有硬币,那么啤酒就在我身上;)

I am not sure if this is relevant in today's world, but double quotes used to be used for content that needed to have control characters processed and single quotes for strings that didn't.我不确定这在当今世界是否相关,但双引号曾经用于需要处理控制字符的内容,而单引号用于不需要处理的字符串。

The compiler will run string manipulation on a double quoted string while leaving a single quoted string literally untouched.编译器将对双引号字符串运行字符串操作,同时保持单引号字符串字面不变。 This used to lead to 'good' developers choosing to use single quotes for strings that didn't contain control characters like \\n or \\0 (not processed within single quotes) and double quotes when they needed the string parsed (at a slight cost in CPU cycles for processing the string).这曾经导致“优秀”的开发人员选择对不包含控制字符的字符串使用单引号,如\\n\\0 (不在单引号内处理)和双引号,当他们需要解析字符串时(以少量成本)在用于处理字符串的 CPU 周期中)。

If you are using JSHint , it will raise an error if you use a double quoted string.如果您正在使用JSHint ,如果您使用双引号字符串,它将引发错误。

I used it through the Yeoman scafflholding of AngularJS, but maybe there is somehow a manner to configure this.我通过 AngularJS 的 Yeoman scafflholding 使用它,但也许有某种方式来配置它。

By the way, when you handle HTML into JavaScript, it's easier to use single quote:顺便说一句,当您将 HTML 处理为 JavaScript 时,使用单引号更容易:

var foo = '<div class="cool-stuff">Cool content</div>';

And at least JSON is using double quotes to represent strings.至少 JSON 使用双引号来表示字符串。

There isn't any trivial way to answer to your question.没有任何简单的方法可以回答您的问题。

Talking about performance, quotes will never be your bottleneck.谈到性能,报价永远不会成为你的瓶颈。 However, the performance is the same in both cases.但是,这两种情况下的性能是相同的。

Talking about coding speed, if you use ' for delimiting a string, you will need to escape " quotes. You are more likely to need to use " inside the string.谈到编码速度,如果使用'来分隔字符串,则需要转义"引号。您更有可能需要在字符串内部使用" Example:例子:

// JSON Objects:
var jsonObject = '{"foo":"bar"}';

// HTML attributes:
document.getElementById("foobar").innerHTML = '<input type="text">';

Then, I prefer to use ' for delimiting the string, so I have to escape fewer characters.然后,我更喜欢使用'来分隔字符串,所以我必须转义更少的字符。

One (silly) reason to use single quotes would be that they don't require you to hit the shift key to type them, whereas a double quote do.使用单引号的一个(愚蠢的)原因是它们不需要您按 shift 键来键入它们,而双引号则可以。 (I'm assuming that the average string doesn't require escaping, which is a reasonable assumption.) Now, let's suppose every day I code 200 lines of code. (我假设平均字符串不需要转义,这是一个合理的假设。)现在,假设我每天编写 200 行代码。 Maybe in those 200 lines I have 30 quotes.也许在这 200 行中我有 30 个引号。 Maybe typing a double quote takes 0.1 seconds more time than typing a single quote (because I have to hit the shift key).也许输入双引号比输入单引号多花 0.1 秒的时间(因为我必须按下 shift 键)。 Then on any given day, I waste 3 seconds.然后在任何一天,我浪费了 3 秒钟。 If I code in this manner for 200 days a year for 40 years, then I've wasted 6.7 hours of my life.如果我以这种方式每年 200 天编码 40 年,那么我浪费了我生命中的 6.7 小时。 Food for thought.深思熟虑。

Examining the pros and cons审查利弊

In favor of single quotes支持单引号

  • Less visual clutter.减少视觉混乱。
  • Generating HTML: HTML attributes are usually delimited by double quotes.生成 HTML:HTML 属性通常用双引号分隔。

 elem.innerHTML = '<a href="' + url + '">Hello</a>';
However, single quotes are just as legal in HTML. 但是,单引号在 HTML 中同样合法。

 elem.innerHTML = "<a href='" + url + "'>Hello</a>";

Furthermore, inline HTML is normally an anti-pattern.此外,内联 HTML 通常是一种反模式。 Prefer templates.更喜欢模板。

  • Generating JSON: Only double quotes are allowed in JSON.生成 JSON:JSON 中只允许使用双引号。

 myJson = '{ "hello world": true }';

Again, you shouldn't have to construct JSON this way.同样,您不应该以这种方式构造 JSON。 JSON.stringify() is often enough. JSON.stringify() 通常就足够了。 If not, use templates.如果没有,请使用模板。

In favor of double quotes赞成双引号

  • Doubles are easier to spot if you don't have color coding.如果您没有颜色编码,则更容易发现双打。 Like in a console log or some kind of view-source setup.就像在控制台日志或某种视图源设置中一样。
  • Similarity to other languages: In shell programming (Bash etc.), single-quoted string literals exist, but escapes are not interpreted inside them.与其他语言的相似之处:在 shell 编程(Bash 等)中,存在单引号字符串文字,但在其中不解释转义符。 C and Java use double quotes for strings and single quotes for characters. C 和 Java 对字符串使用双引号,对字符使用单引号。
  • If you want code to be valid JSON, you need to use double quotes.如果您希望代码是有效的 JSON,则需要使用双引号。

In favor of both赞成双方

There is no difference between the two in JavaScript.两者在 JavaScript 中没有区别。 Therefore, you can use whatever is convenient at the moment.因此,您可以使用目前方便的任何东西。 For example, the following string literals all produce the same string:例如,以下字符串文字都产生相同的字符串:

 "He said: \\"Let's go!\\"" 'He said: "Let\\'s go!"' "He said: \\"Let\\'s go!\\"" 'He said: \\"Let\\'s go!\\"'

Single quotes for internal strings and double for external.内部字符串使用单引号,外部字符串使用双引号。 That allows you to distinguish internal constants from strings that are to be displayed to the user (or written to disk etc.).这允许您将内部常量与要显示给用户(或写入磁盘等)的字符串区分开来。 Obviously, you should avoid putting the latter in your code, but that can't always be done.显然,您应该避免将后者放在您的代码中,但这并不总是可以做到的。

There isn't any difference between single and double quotes in JavaScript. JavaScript 中的单引号和双引号之间没有任何区别。

The specification is important:规范很重要:

Maybe there are performance differences, but they are absolutely minimum and can change any day according to browsers' implementation.也许存在性能差异,但它们绝对是最小的,并且可以根据浏览器的实现随时更改。 Further discussion is futile unless your JavaScript application is hundreds of thousands lines long.除非您的 JavaScript 应用程序长达数十万行,否则进一步讨论是徒劳的。

It's like a benchmark if这就像一个基准,如果

a=b;

is faster than

a = b;

(extra spaces) (额外的空格)

today, in a particular browser and platform, etc.今天,在特定的浏览器和平台等中。

One more thing that you might want to consider as a reason for the shift from double quotes to single quotes is the increase in popularity of server side scripts.作为从双引号转变为单引号的原因,您可能还想考虑的另一件事是服务器端脚本的流行度增加。 When using PHP you can pass variables and parse JavaScript functions using strings and variables in PHP.使用 PHP 时,您可以使用 PHP 中的字符串和变量传递变量和解析 JavaScript 函数。

If you write a string and use double quotes for your PHP you won't have to escape any of the single quotes and PHP will automatically retrieve the value of the variables for you.如果您编写一个字符串并为您的 PHP 使用双引号,您将不必转义任何单引号,PHP 将自动为您检索变量的值。

Example:I need to run a JavaScript function using a variable from my server.示例:我需要使用服务器中的变量运行 JavaScript 函数。

public static function redirectPage( $pageLocation )
{
    echo "<script type='text/javascript'>window.location = '$pageLocation';</script>";
}

This saves me a lot of hassle in having to deal with joining strings, and I can effectively call a JavaScript from PHP.这为我省去了处理连接字符串的很多麻烦,而且我可以有效地从 PHP 调用 JavaScript。 This is only one example, but this may be one of several reasons why programmers are defaulting to single quotes in JavaScript.这只是一个例子,但这可能是程序员在 JavaScript 中默认使用单引号的几个原因之一。

Quote from PHP documents : 引用自 PHP 文档

The most important feature of double-quoted strings is the fact that variable names will be expanded.双引号字符串最重要的特性是变量名将被扩展。 See string parsing for details.有关详细信息,请参阅字符串解析。

There are people that claim to see performance differences: old mailing list thread .有人声称看到了性能差异: 旧邮件列表线程 But I couldn't find any of them to be confirmed.但我找不到任何可以确认的。

The main thing is to look at what kind of quotes (double or single) you are using inside your string.最重要的是查看您在字符串中使用的是哪种引号(双引号或单引号)。 It helps to keep the number of escapes low.它有助于保持较低的逃逸次数。 For instance, when you are working with HTML content inside your strings, it is easier to use single quotes so that you don't have to escape all double quotes around the attributes.例如,当您在字符串中处理 HTML 内容时,使用单引号更容易,这样您就不必转义属性周围的所有双引号。

I've been running the following about 20 times.我已经运行了大约 20 次以下。 And it appears that double quotes are about 20% faster.看起来双引号快了大约 20%。

The fun part is, if you change part 2 and part 1 around, single quotes are about 20% faster.有趣的是,如果您更改第 2 部分和第 1 部分,单引号会快 20% 左右。

//Part1
var r='';
var iTime3 = new Date().valueOf();
for(var j=0; j<1000000; j++) {
    r+='a';
}
var iTime4 = new Date().valueOf();
alert('With single quote : ' + (iTime4 - iTime3));  

//Part 2                
var s="";
var iTime1 = new Date().valueOf();
for(var i=0; i<1000000; i++) {
    s += "a";
}
var iTime2 = new Date().valueOf();
alert('With double quote: ' + (iTime2 - iTime1));

When using CoffeeScript I use double quotes.使用CoffeeScript 时,我使用双引号。 I agree that you should pick either one and stick to it.我同意你应该选择任何一个并坚持下去。 CoffeeScript gives you interpolation when using the double quotes. CoffeeScript 会在使用双引号时为您提供插值。

"This is my #{name}"

ECMAScript 6 is using back ticks (`) for template strings. ECMAScript 6对模板字符串使用反引号 (`)。 Which probably has a good reason, but when coding, it can be cumbersome to change the string literals character from quotes or double quotes to backticks in order to get the interpolation feature.这可能有一个很好的理由,但是在编码时,将字符串文字字符从引号或双引号更改为反引号以获得插值功能可能很麻烦。 CoffeeScript might not be perfect, but using the same string literals character everywhere (double quotes) and always be able to interpolate is a nice feature. CoffeeScript 可能并不完美,但在任何地方使用相同的字符串文字字符(双引号)并且始终能够插入是一个不错的功能。

`This is my ${name}`

I would use double quotes when single quotes cannot be used and vice versa:当不能使用单引号时,我会使用双引号,反之亦然:

"'" + singleQuotedValue + "'"
'"' + doubleQuotedValue + '"'

Instead of:代替:

'\'' + singleQuotedValue + '\''
"\"" + doubleQuotedValue + "\""

如果您在 JavaScript 和 C# 之间来回切换,最好训练您的手指以了解双引号这一常见约定。

Now that it's 2020, we should consider a third option for JavaScript: The single backtick for everything.现在是 2020 年,我们应该考虑 JavaScript 的第三种选择:所有事物的单反引号。

This can be used everywhere instead of single or double quotes.这可以在任何地方使用,而不是单引号或双引号。

It allows you to do all the things!它可以让你做所有的事情!

  1. Embed single quotes inside of it: `It's great!`在其中嵌入单引号: `太棒了!`

  2. Embed double quotes inside of it: `It's "really" great!`在其中嵌入双引号: `它“真的”很棒!`

  3. Use string interpolation: `It's "${better}" than great!`使用字符串插值: `它比“${better}”更好!`

  4. It allows multiple lines: `它允许多行: `

    This这个

    Makes使

    JavaScript JavaScript

    Better!更好的!

` `

It also doesn't cause any performance loss when replacing the other two: Are backticks (``) slower than other strings in JavaScript?在替换其他两个字符串时,它也不会造成任何性能损失: 反引号 (``) 是否比 JavaScript 中的其他字符串慢?

在阅读了所有说它可能更快或可能有优势的答案后,我会说双引号更好或可能更快,因为Google Closure 编译器将单引号转换为双引号。

There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JavaScript code itself is in a string), to keep number of escapes low.严格来说没有区别,因此主要是品味和字符串中的内容(或者 JavaScript 代码本身是否在字符串中)的问题,以保持较低的转义次数。

The speed difference legend might come from PHP world, where the two quotes have different behavior.速度差异图例可能来自 PHP 世界,其中两个引号具有不同的行为。

If your JavaScript source is如果您的 JavaScript 源代码是

elem.innerHTML="<img src='smily' alt='It\'s a Smily' style='width:50px'>";

the HTML source will be: HTML 源代码将是:

<img src="smiley" alt="It's a Smiley" style="width:50px">

Or for HTML5或者对于 HTML5

<img src=smiley alt="It's a Smiley" style=width:50px>

JavaScript allows arrays like that: JavaScript 允许这样的数组:

var arr=['this','that'];

But if you stringify it, it will be for compatibility reasons:但是,如果您将其字符串化,则是出于兼容性原因:

JSON=["this","that"]

I'm sure this takes some time.我确定这需要一些时间。

Just to add my two cents : In working with both JavaScript and PHP a few years back, I've become accustomed to using single quotes so I can type the escape character ('') without having to escape it as well.补充一下我的两分钱:几年前在使用 JavaScript 和 PHP 时,我已经习惯于使用单引号,这样我就可以输入转义字符 ('') 而不必对其进行转义。 I usually used it when typing raw strings with file paths, etc.我通常在输入带有文件路径等的原始字符串时使用它。

Anyhow, my convention ended up becoming the use of single quotes on identifier-type raw strings, such as if (typeof s == 'string') ... (in which escape characters would never be used - ever), and double quotes for texts , such as "Hey, what's up?".无论如何,我的约定最终变成在标识符类型的原始字符串上使用单引号,例如if (typeof s == 'string') ... (其中永远不会使用转义字符 - 永远)和双引号对于文本,例如“嘿,怎么了?”。 I also use single quotes in comments as a typographical convention to show identifier names.我还在注释中使用单引号作为显示标识符名称的排版约定。 This is just a rule of thumb, and I break off only when needed, such as when typing HTML strings '<a href="#"> like so <a>' (though you could reverse the quotes here also).这只是一个经验法则,我只在需要时中断,例如在键入 HTML 字符串'<a href="#"> like so <a>' (尽管您也可以在此处反转引号)。 I'm also aware that, in the case of JSON, double quotes are used for the names - but outside that, personally, I prefer the single quotes when escaping is never required for the text between the quotes - like document.createElement('div') .我也知道,在JSON的情况下,双引号被用于名字-但外面个人而言,我更喜欢单引号时,从来没有要求转义引号之间的文本-就像document.createElement('div')

The bottom line is, and as some have mentioned/alluded to, to pick a convention, stick with it, and only deviate when necessary.底线是,正如一些人提到/暗示的那样,选择一个约定,坚持它,并且只在必要时偏离。

You can use single quotes or double quotes. 您可以使用单引号或双引号。 This enables you for example to easily nest javascript inside HTML attributes, without the need to escape the quotes. 例如,这使您能够轻松地将javascript嵌套在HTML属性中,而无需转义引号。 The same is when you create javascript with PHP. 使用PHP创建javascript时也是如此。

The general idea is: if it is possible use such quotes that you won't need to escape. 一般的想法是:如果可能的话,使用您不需要转义的引号。 Less escaping = better code. 更少的转义=更好的代码。

It is just a matter time for me.这对我来说只是时间问题。 A few milliseconds lost of my life every time I have to press the Shift key before every time I'm able to type " .每次我必须按Shift键,然后才能输入"时,我的生命会损失几毫秒。

I prefer ' simply because you don't have to do it!我更喜欢'只是因为你不必这样做!

Other than that, you can escape a ' inside single quotes with backslash \\' .除此之外,你可以逃脱'内单引号用反斜杠\\'

console.log('Don\\'t lose time'); // "Don't lose time"

For me, if I code in a Vim editor and if something is enclosed in single quotes, I can double-click to select only the text within the quotes.对我来说,如果我在Vim编辑器中编写代码并且某些内容被单引号括起来,我可以双击以选择引号内的文本。 Double quotes, on the other hand, include the quote marks which I find annoying when I want to do some quick copy and pasting.另一方面,双引号包括引号,当我想做一些快速复制和粘贴时,我觉得这很烦人。

Eg 'myVar' double-click in the Vim editor copies: >myVar< "myVar" literally copies: >"myVar"< and when I paste, I have to delete the quote marks on either side.例如,在 Vim 编辑器中双击 'myVar' 复制: >myVar< "myVar" 字面复制:>"myVar"< 并且当我粘贴时,我必须删除两边的引号。

The difference is purely stylistic.区别纯粹是风格上的。 I used to be a double-quote Nazi.我曾经是一个双引号纳粹。 Now I use single quotes in nearly all cases.现在我几乎在所有情况下都使用单引号。 There's no practical difference beyond how your editor highlights the syntax.除了您的编辑器突出显示语法的方式之外,没有任何实际区别。

I use single quotes most of the time, because when developing in PHP, single quoted-string are in no way altered, which is what I want.我大部分时间都使用单引号,因为在 PHP 中开发时,单引号字符串绝不会改变,这就是我想要的。 When I use当我使用

echo "$xyz";

In PHP, $xyz gets evaluated, which is not what I want.在 PHP 中, $xyz 被评估,这不是我想要的。 Therefore I always use ' instead of " when it comes to web development. So I ensure at least string-consistency when it comes to PHP/JavaScript.因此,当涉及到 Web 开发时,我总是使用'而不是" 。因此,当涉及到 PHP/JavaScript 时,我至少确保字符串的一致性。

Unfortunately this can't be done in Java or Objective-C , where '' stands for character and "" stands for string.不幸的是,这不能在 Java 或Objective-C 中完成,其中''代表字符而""代表字符串。 But this is another question.但这是另一个问题。

If you use PHP to generate JavaScript code you should use the following declaration.如果您使用 PHP 生成 JavaScript 代码,则应使用以下声明。

let value = "<?php echo 'This is my message, "double quoted" - \'single quoted\' ?>";

The output will be:输出将是:

This is my message, "double quoted" - 'single quoted'

For some reasons it is recommend to use single quotes rather than double quotes in PHP.出于某些原因,建议在 PHP 中使用单引号而不是双引号。

For the normal behaviour in JavaScript it is recommend to use single quotes.对于 JavaScript 中的正常行为,建议使用单引号。

 var value = 'This is my message'; document.getElementById('sample-text').innerHTML = value;
 <span id="sample-text"></span>

I think it's important not to forget that while Internet Explorer might have zero extensions/toolbars installed, Firefox might have some extensions installed (I'm just thinking of Firebug for instance).我认为重要的是不要忘记,虽然 Internet Explorer 可能安装了零个扩展/工具栏,但 Firefox 可能安装了一些扩展(例如,我只是在考虑Firebug )。 Those extensions will have an influence on the benchmark result.这些扩展会对基准测试结果产生影响。

Not that it really matters since browser X is faster in getting elementstyles, while browser Y might be faster in rendering a canvas element (hence why a browser "manufacturer" always has the fastest JavaScript engine).这并不重要,因为浏览器 X 在获取元素样式方面更快,而浏览器 Y 在呈现画布元素方面可能更快(因此浏览器“制造商”总是拥有最快的 JavaScript 引擎)。

I think this is all a matter of convenience/preference.我认为这完全是一个方便/偏好的问题。

I prefer double quote because it matches what C# has and this is my environment that I normally work in: C# + JavaScript.我更喜欢双引号,因为它匹配 C# 所拥有的,这是我通常使用的环境:C# + JavaScript。

Also one possible reason for double quotes over single quotes is this (which I have found in my projects code): French or some other languages use single quotes a lot (like English actually), so if by some reason you end up rendering strings from the server side (which I know is bad practice), then a single quote will render wrongly.双引号超过单引号的另一个可能原因是(我在我的项目代码中找到了):法语或其他一些语言经常使用单引号(实际上就像英语),所以如果由于某种原因你最终从服务器端(我知道这是不好的做法),那么单引号将错误地呈现。

The probability of using double quotes in a regular language is low, and therefore I think it has a better chance of not breaking something.在常规语言中使用双引号的可能性很低,因此我认为它有更好的机会不破坏某些东西。

Personally I prefer single quotes for the sake of readability.为了可读性,我个人更喜欢单引号。 If I'm staring at code all day it's easier to see the words with just single quotes as opposed to double quotes.如果我整天盯着代码看,只用单引号而不是双引号更容易看到单词。

Easier to read as demonstrated here:更易于阅读,如下所示:

'easy to read' '易于阅读'

"harder to read" “更难读”

""hardest to read"" ""最难读""

I prefer to use the single quote, ' .我更喜欢使用单引号' It is easier to type and looks better.打字更容易,看起来更好。

Also, let's remember that straight quotes (single and double) are a mistake in good typography.另外,让我们记住直引号(单引号和双引号)在良好的排版中是一个错误。 Curly quotes are preferable, so instead of escaping straight quotes I prefer to use the correct characters.卷曲引号更可取,因此我更喜欢使用正确的字符而不是转义直引号。

const message = 'That\'s a \'magic\' shoe.' // This is wrong
const message = 'That’s a ‘magic’ shoe.' // This is correct

https://practicaltypography.com/straight-and-curly-quotes.html https://practicaltypography.com/straight-and-curly-quotes.html

Can someone add a smart-quote feature to Visual Studio Code, please?有人可以向 Visual Studio Code 添加智能引用功能吗?

In addition, it seems the specification (currently mentioned at MDN ) doesn't state any difference between single and double quotes except closing and some unescaped few characters.此外,除了关闭和一些未转义的几个字符外,规范(目前在MDN 中提到)似乎没有说明单引号和双引号之间的任何区别。 However, template literal (`) assumes additional parsing/processing.但是,模板文字 (`) 需要额外的解析/处理。

A string literal is 0 or more Unicode code points enclosed in single or double quotes.字符串文字是用单引号或双引号括起来的 0 个或多个 Unicode 代码点。 Unicode code points may also be represented by an escape sequence. Unicode 代码点也可以由转义序列表示。 All code points may appear literally in a string literal except for the closing quote code points , U+005C (REVERSE SOLIDUS) , U+000D (CARRIAGE RETURN) , and U+000A (LINE FEED) .除了结束引号代码点U+005C (REVERSE SOLIDUS)U+000D (CARRIAGE RETURN) U+000A (LINE FEED) U+000D (CARRIAGE RETURN)U+000A (LINE FEED)之外,所有代码点都可以字面出现在字符串文字中 Any code points may appear in the form of an escape sequence.任何代码点都可能以转义序列的形式出现。 String literals evaluate to ECMAScript String values...字符串文字评估为 ECMAScript 字符串值...

Source: https://tc39.es/ecma262/#sec-literals-string-literals来源: https : //tc39.es/ecma262/#sec-literals-string-literals

This answer is going to be pretty much useless but my general guideline is using double quotes for when a string is going to be visible to the user and single quotes for when it's passed down into a function exclusively.这个答案几乎没有用,但我的一般准则是在字符串对用户可见时使用双引号,在将字符串专门传递到 function 时使用单引号。 Jshint w109 however suggests single quote strings but it's personal preference from my experience mostly然而,Jshint w109 建议使用单引号字符串,但根据我的经验,这主要是个人偏好

As stated by other replies, they are almost the same.正如其他回复所述,它们几乎相同。 But I will try to add more.但我会尝试添加更多。

  1. Some efficient algorithms use character arrays to process strings.一些有效的算法使用字符数组来处理字符串。 Those algorithms (browser compiler, etc.) would see " (#34) first before ' (#39) therefore saving several CPU cycles depending on your data structure.这些算法(浏览器编译器等)会在' (#39) 之前首先看到" (#34),因此根据您的数据结构节省了几个 CPU 周期。
  2. " is escaped by anti- XSS engines "被反XSS引擎逃脱

For use of JavaScript code across different languages, I've found single quotes to consistently require less code tweaking.为了跨不同语言使用 JavaScript 代码,我发现单引号始终需要较少的代码调整。

Double quotes support multi-line strings.双引号支持多行字符串。

Single quotation ( ' ) uses one keyboard key, but double quotation uses two keys ( shift + ' ).单引号 ( ' ) 使用一个键盘键,但双引号使用两个键 ( shift + ' )。 So saving the number of keys press is also an advantage: (:所以节省按键次数也是一个优势:(:

The best practice is to use double quotes ("") first and single quotes ('') if needed after.最佳做法是先使用双引号 (""),然后根据需要使用单引号 ('')。 The reason being is that if you ever use server-side scripting you will not be able to pull content from a server (example SQL queries from a database) if you use singles quotes over double.原因是如果您曾经使用服务器端脚本,如果您使用双引号,您将无法从服务器中提取内容(例如来自数据库的 SQL 查询)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM