console.log("double");
vs console.log('single');
console.log(“双”);vs console.log(“单”);
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.
我看到越来越多的JavaScript库在处理字符串时使用单引号。为什么要用一个来代替另一个呢?我觉得它们是可以互换的。
41 个解决方案
#1
1008
The most likely reason for use of single vs double in different libraries is programmer preference and/or API consistency.
在不同的库中,使用单和双的最可能的原因是程序员偏好和/或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'");
…but this can get complicated…
但这可能会变得很复杂……
alert("It's \"game\" time.");
alert('It\'s "game" time.');
Another option, new in ES6, are Template literals which use the back-tick
character:
另一种选择,在ES6中是新的,是使用后勾字符的模板文字:
alert(`Use "double" and 'single' quotes in the same string`);
alert(`The escape the \` back-tick character in a string`);
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
模板文本提供了一个干净的语法:变量内插、多行字符串等等。
#2
554
If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. 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,应该注意的是,严格地说,JSON字符串必须是双引号。当然,许多库也支持单引号,但是我在我的一个项目中遇到了很大的问题,然后才意识到单引号实际上并不是JSON标准。
#3
230
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'
. - 双引号消除了省略撇号(如收缩)的需要。考虑一下绳子:“我要去购物中心”,而另一种说法是:“我要去购物中心”。
-
Double quotes mean a string in many other languages. When you learn a new language like Java or C, double quotes are always used. In Ruby, PHP and Perl, single-quoted strings imply no backslash escapes while double quotes support them.
双引号表示许多其他语言中的字符串。当你学习一种新的语言,比如Java或C语言时,总是使用双引号。在Ruby、PHP和Perl中,单引号字符串表示没有反斜杠转义,而双引号支持它们。
-
JSON notation is written with double quotes.
JSON符号是用双引号写的。
Nonetheless, as others have stated, it is most important to remain consistent.
尽管如此,正如其他人所说,保持一致是最重要的。
#4
111
The only difference is demonstrated in the following:
唯一的区别体现在以下几个方面:
'A string that\'s single quoted'
"A string that's double quoted"
So, it's only down to how much quote escaping you want to do. Obviously the same applies to double quotes in double quoted strings.
所以,这只取决于你想要做多少报价。显然,双引号在双引号字符串中同样适用。
#5
61
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:
单引号:
- airbnb
- airbnb
- 脸谱网
- 谷歌
- grunt
- 咕哝着说
- gulp
- 狼吞虎咽地吃
- node
- 节点
- npm (though not defined in author's guide)
- npm(虽然没有在作者的指南中定义)
- wikimedia
- 维基
- wordpress
- wordpress
- yandex
- yandex
No preference:
没有偏好:
- three.js
- three.js
Double quotes:
双引号:
#6
52
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 IE7 and IE8), this will return the following:
在Safari、Chrome、Opera和Internet Explorer(在IE7和IE8中测试),这将返回以下内容:
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. One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.
单引号已经被双引号取代。(同时也要注意缩进空间是如何被四个空间所取代的。)这给人的印象是,至少有一个浏览器在内部解析JavaScript,就好像所有东西都是用双引号写的一样。人们可能会认为,如果一切都按照这个“标准”来写的话,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.
结论:我认为我们需要做更多的研究。
Edit: 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. I found no difference at all in Opera.
似乎单引号在资源管理器窗口中的速度有时更快(我的测试中大约有三分之一显示的响应时间更快),但是如果Mozilla显示出不同,它处理双引号的速度会稍微快一些。我发现歌剧没有什么不同。
Edit 2014: Modern versions of Firefox/Spidermonkey don’t do this anymore.
编辑2014:Firefox/Spidermonkey的现代版本不再这样做了。
#7
29
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(可能是“不好的”事情,但是避免讨论)单引号是字符串文本的惟一选项,我相信。
e.g., 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. Even "
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. \"
won't work either because at this point you're escaping for HTML, not JavaScript.
但是你不能用双引号来包裹“hi”,通过任何我知道的转义方法。甚至“;这可能是我最好的猜测(因为你在HTML的属性值中转义了引号)在Firefox中对我不起作用。也不会工作,因为在这一点上,你是为了HTML而不是JavaScript。
So, if the name of the game is consistency, and you're going to do some inline JavaScript in parts of your app, I think single quotes are the winner. Someone please correct me if I'm wrong though.
所以,如果游戏的名称是一致的,并且你将在你的应用程序的某些部分做一些内联JavaScript,我认为单引号是赢家。如果我错了,请纠正我。
#8
29
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先生改变了主意,现在推荐使用双引号:)
#9
22
Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.
严格地说,意义上没有区别;所以这个选择就很方便了。
Here are several factors that could influence your choise:
以下是影响你选择的几个因素:
- House style: Some groups of developers already use one convention or the other.
- 房屋风格:一些开发人员已经使用了一个约定或另一个。
- 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 java-script so that the scripts can be built server-side (VB.Net uses double-quotes for strings, so the java-script strings are easy to distinguished if they use single quotes).
- 服务器端语言:VB。Net用户可以选择使用java脚本的单引号,这样脚本就可以构建服务器端(VB)。Net对字符串使用双引号,因此如果使用单引号,java脚本字符串很容易区分。
- 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 thing one or other style looks better.
- 个人喜好:你可以选择一种或其他样式更好。
#10
18
Let's look what a reference do.
让我们看看引用是怎么做的。
Inside jquery.js, every string are double-quoted.
在jquery。js,每个字符串都是双引号。
So, beginning now, I'll use double-quoted strings. (I was using single!)
因此,从现在开始,我将使用双引号字符串。(我用单!)
#11
13
I hope I am not adding something obvious, but I have been struggling with Django and Ajax and JSON on this.
我希望我没有添加一些明显的东西,但是我一直在为Django和Ajax和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 probably it doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles. You should know what is actually escaping, reading, passing your string.
我的底线是:在JavaScript中,这并不重要,但是一旦你把它嵌入到HTML中或者你开始遇到麻烦。你应该知道什么是真正的逃避,阅读,传递你的弦。
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 on single quotes... .. I guess..
原因很清楚,但也很清楚为什么我们应该坚持单引号……我猜. .
This case is a very simple HTML embedding, 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. It might save a couple of debug issues...
在HTML中尝试使用单引号。它可能会节省几个调试问题……
#12
12
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 . Eg let's say you getting into Node.js. Take a look at core modules, eg underscore.js or express and see what convention they use, and consider following that.
如果你独自一人进行了几个项目的黑客攻击,那么你可以看看社区里一些杰出的领导者。假设你进入了Node.js。看看核心模块(如下划线)。js或express,看看他们使用了什么约定,然后考虑一下。
-
If both conventions are equally used, then defer to your personal
preference.如果两种习惯都同样适用,那就遵从你的个人喜好。
-
If you have no personal preference, then flip a coin.
如果你没有个人偏好,那就抛硬币吧。
-
If you don't have a coin, then beer is on me ;)
如果你没有硬币,我就喝啤酒;
#13
11
Not sure if this is relevant in todays 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周期中稍微花费一些成本)。
#14
11
If you are using jshint, it will raise an error if you use double quote string.
如果您使用的是jshint,如果使用双引号字符串,则会引起错误。
I used it through the Yeoman scafflholding of AngularJS but maybe there is somehow a maner to configure this.
我用它通过了AngularJS的Yeoman脚手架,但可能有一个配置这个的maner。
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 reprensent strings.
至少JSON使用双引号来重新发送字符串。
There is no trivial way to answer to your question
你的问题没有简单的答案。
#15
9
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, in 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 less characters.
然后,我更喜欢用“来分隔字符串,所以我必须避免使用更少的字符”。
#16
9
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
ES6 update
ES6更新
Using template literal syntax.
使用模板文字语法。
`Be "my" guest. You're in complete freedom.`; // most comfort :D
#17
8
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>';
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
Furthermore, inline HTML is normally an anti-pattern. Prefer templates.
此外,内联HTML通常是反模式的。喜欢的模板。
- 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.stringify() is often enough. If not, use templates.
同样,您不应该这样构造JSON。JSON.stringify()通常是足够的。如果没有,使用模板。
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. C and Java use double quotes for strings and single quotes for characters.
- 与其他语言相似:在shell编程(Bash等)中,单引号字符串是存在的,但是转义在它们内部没有解释。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. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:
在JavaScript中两者没有区别。因此,您现在可以使用任何方便的方法。例如,下列字符串字面量都产生相同的字符串:
"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.
内部字符串单引号,外部双引号。这允许您将内部常量与要显示给用户的字符串(或写入磁盘等)区分开来。显然,您应该避免将后者放在代码中,但这并不总是可以做到的。
#18
7
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. This is only one example, but this may be one of several reasons why programmers are defaulting to single quotes in javascript.
这节省了我处理连接字符串的麻烦,而且我可以有效地从PHP调用javascript。这只是一个例子,但这可能是程序员在javascript中默认单引号的几个原因之一。
Quote from PHP documents: "The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details. "
引用PHP文档:“双引号字符串最重要的特性是变量名会被扩展。有关详细信息,请参见字符串解析。”
#19
7
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. (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. Maybe in those 200 lines I have 30 quotes. Maybe typing a double quote takes 0.1 seconds more time than typing a single quote (because I have to hit the shift key). Then on any given day, I waste 3 seconds. If I code in this manner for 200 days a year for 40 years, then I've wasted 6.7 hours of my life. Food for thought.
使用单引号的一个(愚蠢的)理由是,它们不需要您按shift键来键入它们,而双引号可以。(我假设平均字符串不需要转义,这是一个合理的假设。)现在,假设每天我编码200行代码。可能在这200行中,我有30条引语。也许输入双引号比输入单引号花费0.1秒(因为我必须按shift键)。然后在任何一天,我浪费3秒。如果我以这种方式编码,一年有200天,40年,那么我就浪费了6.7小时的生命。精神食粮。
#20
5
I would use double quotes when single quotes cannot be used and vice versa:
当单引号不能使用时,我将使用双引号,反之亦然:
"'" + singleQuotedValue + "'"
'"' + doubleQuotedValue + '"'
Instead of:
而不是:
'\'' + singleQuotedValue + '\''
"\"" + doubleQuotedValue + "\""
#21
5
When using CoffeeScript I use double quotes. I agree that you should pick either one and stick to it. CoffeeScript gives you interpolation when using the double quotes.
使用CoffeeScript时,我使用双引号。我同意你应该随便挑一个,然后坚持下去。当使用双引号时,CoffeeScript会给你插值。
"This is my #{name}"
ES6 is using back ticks (`) for template strings. 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 back ticks 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.
ES6使用back ticks(')用于模板字符串。这可能有一个很好的理由,但是当编码时,将字符串文字字符从引号或双引号转换为回调函数以获得插值特性是很麻烦的。CoffeeScript可能不是完美的,但是使用相同的字符串文字字符(双引号)并且总是能够插入是一个很好的特性。
`This is my ${name}`
#22
4
If you're jumping back an forth between JavaScript and C#, it's best to train your fingers for the common convention which is double quotes.
如果您在JavaScript和c#之间来回跳转,最好是为通用约定训练您的手指,这是双引号。
#23
4
There is no difference between single and double quotes in JavaScript.
在JavaScript中,单引号和双引号之间没有区别。
Specification is important:
规范是重要的:
Maybe there are performance diffs, but they are absolutely minimum and can change everyday according to browsers' implementation. Further discussion is futile unless your JavaScript application is hundreds of thousands 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.
今天,在一个特定的浏览器和平台,等等。
#24
3
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 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时,使用单引号更容易,这样您就不必在属性周围转义所有双引号。
#25
3
I've been running the following about 20 times. And it appears that double quotes are about 20% faster.
我已经跑了20次了。而且双引号的速度快了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));
#26
2
After reading all the answers that say it maybe be faster or maybe have advantages, I would say double quote is better or maybe faster too because Google closure compiler convert single quotes to double quotes.
在读完所有的答案后,我认为双引号更好,或者可能更快,因为谷歌关闭编译器将单引号转换为双引号。
#27
2
If your JS source is:
如果你的JS来源是:
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>
JS allows arrays like that:
JS允许这样的数组:
var arr=['this','that'];
But if you stringify it, it will be for compatibly reason:
但是如果你把它捆起来,它会有一个相容性的原因:
JSON=["this","that"]
I'm sure this takes some time.
我相信这需要一些时间。
#28
2
Just to add my 2 cents: In working with both JS and PHP a few years back, I've become accustom to using single quotes so I can type the escape character ('\') without having to escape it as well. I usually used it when typing raw strings with file paths, etc. (http://en.wikipedia.org/wiki/String_literal#Raw_strings)
只需添加我的2美分:几年前在使用JS和PHP时,我已经习惯于使用单引号,这样我就可以键入escape字符('\'),而不需要逃离它。我通常在用文件路径键入原始字符串时使用它(http://en.wikipedia.org/wiki/String_literal#Raw_strings)。
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?". 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). 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')
.
无论如何,我的约定最终变成了在标识符类型的原始字符串上使用单引号,比如if (s == 'string')…(在其中转义字符永远不会被使用)和双引号,比如“嘿,怎么了?”我还在注释中使用单引号作为显示标识符名称的版式约定。这只是一个经验法则,我只在需要时才会中断,比如在键入HTML string '
Bottom line, and as some have mentioned/alluded to, pick a convention, stick with it, and only deviate when necessary.
底线,正如一些人提到的,选择一个惯例,坚持它,并且只在必要时偏离。
#29
2
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. The same is when you create javascript with PHP.
您可以使用单引号或双引号。这使您能够轻松地在HTML属性内嵌套javascript,而无需转义引号。在使用PHP创建javascript时也是如此。
The general idea is: if it is possible use such quotes that you won't need to escape. Less escaping = better code.
一般的想法是:如果有可能使用这样的引用,你就不需要逃避。更少的转义=更好的代码。
#30
1
There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JS code itself is in a string), to keep number of escapes low.
严格来说没有区别,所以这主要是一个味道和字符串(或者如果JS代码本身是字符串)的问题,以保持低的溢出。
The speed difference legend might come from PHP world, where the two quotes have different behavior.
速度差异的传说可能来自于PHP世界,在这里,这两个引用有不同的行为。
#1
1008
The most likely reason for use of single vs double in different libraries is programmer preference and/or API consistency.
在不同的库中,使用单和双的最可能的原因是程序员偏好和/或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'");
…but this can get complicated…
但这可能会变得很复杂……
alert("It's \"game\" time.");
alert('It\'s "game" time.');
Another option, new in ES6, are Template literals which use the back-tick
character:
另一种选择,在ES6中是新的,是使用后勾字符的模板文字:
alert(`Use "double" and 'single' quotes in the same string`);
alert(`The escape the \` back-tick character in a string`);
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
模板文本提供了一个干净的语法:变量内插、多行字符串等等。
#2
554
If you're dealing with JSON, it should be noted that strictly speaking, JSON strings must be double quoted. 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,应该注意的是,严格地说,JSON字符串必须是双引号。当然,许多库也支持单引号,但是我在我的一个项目中遇到了很大的问题,然后才意识到单引号实际上并不是JSON标准。
#3
230
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'
. - 双引号消除了省略撇号(如收缩)的需要。考虑一下绳子:“我要去购物中心”,而另一种说法是:“我要去购物中心”。
-
Double quotes mean a string in many other languages. When you learn a new language like Java or C, double quotes are always used. In Ruby, PHP and Perl, single-quoted strings imply no backslash escapes while double quotes support them.
双引号表示许多其他语言中的字符串。当你学习一种新的语言,比如Java或C语言时,总是使用双引号。在Ruby、PHP和Perl中,单引号字符串表示没有反斜杠转义,而双引号支持它们。
-
JSON notation is written with double quotes.
JSON符号是用双引号写的。
Nonetheless, as others have stated, it is most important to remain consistent.
尽管如此,正如其他人所说,保持一致是最重要的。
#4
111
The only difference is demonstrated in the following:
唯一的区别体现在以下几个方面:
'A string that\'s single quoted'
"A string that's double quoted"
So, it's only down to how much quote escaping you want to do. Obviously the same applies to double quotes in double quoted strings.
所以,这只取决于你想要做多少报价。显然,双引号在双引号字符串中同样适用。
#5
61
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:
单引号:
- airbnb
- airbnb
- 脸谱网
- 谷歌
- grunt
- 咕哝着说
- gulp
- 狼吞虎咽地吃
- node
- 节点
- npm (though not defined in author's guide)
- npm(虽然没有在作者的指南中定义)
- wikimedia
- 维基
- wordpress
- wordpress
- yandex
- yandex
No preference:
没有偏好:
- three.js
- three.js
Double quotes:
双引号:
#6
52
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 IE7 and IE8), this will return the following:
在Safari、Chrome、Opera和Internet Explorer(在IE7和IE8中测试),这将返回以下内容:
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. One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.
单引号已经被双引号取代。(同时也要注意缩进空间是如何被四个空间所取代的。)这给人的印象是,至少有一个浏览器在内部解析JavaScript,就好像所有东西都是用双引号写的一样。人们可能会认为,如果一切都按照这个“标准”来写的话,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.
结论:我认为我们需要做更多的研究。
Edit: 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. I found no difference at all in Opera.
似乎单引号在资源管理器窗口中的速度有时更快(我的测试中大约有三分之一显示的响应时间更快),但是如果Mozilla显示出不同,它处理双引号的速度会稍微快一些。我发现歌剧没有什么不同。
Edit 2014: Modern versions of Firefox/Spidermonkey don’t do this anymore.
编辑2014:Firefox/Spidermonkey的现代版本不再这样做了。
#7
29
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(可能是“不好的”事情,但是避免讨论)单引号是字符串文本的惟一选项,我相信。
e.g., 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. Even "
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. \"
won't work either because at this point you're escaping for HTML, not JavaScript.
但是你不能用双引号来包裹“hi”,通过任何我知道的转义方法。甚至“;这可能是我最好的猜测(因为你在HTML的属性值中转义了引号)在Firefox中对我不起作用。也不会工作,因为在这一点上,你是为了HTML而不是JavaScript。
So, if the name of the game is consistency, and you're going to do some inline JavaScript in parts of your app, I think single quotes are the winner. Someone please correct me if I'm wrong though.
所以,如果游戏的名称是一致的,并且你将在你的应用程序的某些部分做一些内联JavaScript,我认为单引号是赢家。如果我错了,请纠正我。
#8
29
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先生改变了主意,现在推荐使用双引号:)
#9
22
Strictly speaking, there is no difference in meaning; so the choice comes down to convenience.
严格地说,意义上没有区别;所以这个选择就很方便了。
Here are several factors that could influence your choise:
以下是影响你选择的几个因素:
- House style: Some groups of developers already use one convention or the other.
- 房屋风格:一些开发人员已经使用了一个约定或另一个。
- 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 java-script so that the scripts can be built server-side (VB.Net uses double-quotes for strings, so the java-script strings are easy to distinguished if they use single quotes).
- 服务器端语言:VB。Net用户可以选择使用java脚本的单引号,这样脚本就可以构建服务器端(VB)。Net对字符串使用双引号,因此如果使用单引号,java脚本字符串很容易区分。
- 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 thing one or other style looks better.
- 个人喜好:你可以选择一种或其他样式更好。
#10
18
Let's look what a reference do.
让我们看看引用是怎么做的。
Inside jquery.js, every string are double-quoted.
在jquery。js,每个字符串都是双引号。
So, beginning now, I'll use double-quoted strings. (I was using single!)
因此,从现在开始,我将使用双引号字符串。(我用单!)
#11
13
I hope I am not adding something obvious, but I have been struggling with Django and Ajax and JSON on this.
我希望我没有添加一些明显的东西,但是我一直在为Django和Ajax和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 probably it doesn't matter, but as soon as you embed it inside HTML or the like you start to get troubles. You should know what is actually escaping, reading, passing your string.
我的底线是:在JavaScript中,这并不重要,但是一旦你把它嵌入到HTML中或者你开始遇到麻烦。你应该知道什么是真正的逃避,阅读,传递你的弦。
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 on single quotes... .. I guess..
原因很清楚,但也很清楚为什么我们应该坚持单引号……我猜. .
This case is a very simple HTML embedding, 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. It might save a couple of debug issues...
在HTML中尝试使用单引号。它可能会节省几个调试问题……
#12
12
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 . Eg let's say you getting into Node.js. Take a look at core modules, eg underscore.js or express and see what convention they use, and consider following that.
如果你独自一人进行了几个项目的黑客攻击,那么你可以看看社区里一些杰出的领导者。假设你进入了Node.js。看看核心模块(如下划线)。js或express,看看他们使用了什么约定,然后考虑一下。
-
If both conventions are equally used, then defer to your personal
preference.如果两种习惯都同样适用,那就遵从你的个人喜好。
-
If you have no personal preference, then flip a coin.
如果你没有个人偏好,那就抛硬币吧。
-
If you don't have a coin, then beer is on me ;)
如果你没有硬币,我就喝啤酒;
#13
11
Not sure if this is relevant in todays 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周期中稍微花费一些成本)。
#14
11
If you are using jshint, it will raise an error if you use double quote string.
如果您使用的是jshint,如果使用双引号字符串,则会引起错误。
I used it through the Yeoman scafflholding of AngularJS but maybe there is somehow a maner to configure this.
我用它通过了AngularJS的Yeoman脚手架,但可能有一个配置这个的maner。
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 reprensent strings.
至少JSON使用双引号来重新发送字符串。
There is no trivial way to answer to your question
你的问题没有简单的答案。
#15
9
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, in 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 less characters.
然后,我更喜欢用“来分隔字符串,所以我必须避免使用更少的字符”。
#16
9
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
ES6 update
ES6更新
Using template literal syntax.
使用模板文字语法。
`Be "my" guest. You're in complete freedom.`; // most comfort :D
#17
8
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>';
elem.innerHTML = "<a href='" + url + "'>Hello</a>";
Furthermore, inline HTML is normally an anti-pattern. Prefer templates.
此外,内联HTML通常是反模式的。喜欢的模板。
- 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.stringify() is often enough. If not, use templates.
同样,您不应该这样构造JSON。JSON.stringify()通常是足够的。如果没有,使用模板。
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. C and Java use double quotes for strings and single quotes for characters.
- 与其他语言相似:在shell编程(Bash等)中,单引号字符串是存在的,但是转义在它们内部没有解释。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. Therefore, you can use whatever is convenient at the moment. For example, the following string literals all produce the same string:
在JavaScript中两者没有区别。因此,您现在可以使用任何方便的方法。例如,下列字符串字面量都产生相同的字符串:
"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.
内部字符串单引号,外部双引号。这允许您将内部常量与要显示给用户的字符串(或写入磁盘等)区分开来。显然,您应该避免将后者放在代码中,但这并不总是可以做到的。
#18
7
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. This is only one example, but this may be one of several reasons why programmers are defaulting to single quotes in javascript.
这节省了我处理连接字符串的麻烦,而且我可以有效地从PHP调用javascript。这只是一个例子,但这可能是程序员在javascript中默认单引号的几个原因之一。
Quote from PHP documents: "The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details. "
引用PHP文档:“双引号字符串最重要的特性是变量名会被扩展。有关详细信息,请参见字符串解析。”
#19
7
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. (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. Maybe in those 200 lines I have 30 quotes. Maybe typing a double quote takes 0.1 seconds more time than typing a single quote (because I have to hit the shift key). Then on any given day, I waste 3 seconds. If I code in this manner for 200 days a year for 40 years, then I've wasted 6.7 hours of my life. Food for thought.
使用单引号的一个(愚蠢的)理由是,它们不需要您按shift键来键入它们,而双引号可以。(我假设平均字符串不需要转义,这是一个合理的假设。)现在,假设每天我编码200行代码。可能在这200行中,我有30条引语。也许输入双引号比输入单引号花费0.1秒(因为我必须按shift键)。然后在任何一天,我浪费3秒。如果我以这种方式编码,一年有200天,40年,那么我就浪费了6.7小时的生命。精神食粮。
#20
5
I would use double quotes when single quotes cannot be used and vice versa:
当单引号不能使用时,我将使用双引号,反之亦然:
"'" + singleQuotedValue + "'"
'"' + doubleQuotedValue + '"'
Instead of:
而不是:
'\'' + singleQuotedValue + '\''
"\"" + doubleQuotedValue + "\""
#21
5
When using CoffeeScript I use double quotes. I agree that you should pick either one and stick to it. CoffeeScript gives you interpolation when using the double quotes.
使用CoffeeScript时,我使用双引号。我同意你应该随便挑一个,然后坚持下去。当使用双引号时,CoffeeScript会给你插值。
"This is my #{name}"
ES6 is using back ticks (`) for template strings. 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 back ticks 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.
ES6使用back ticks(')用于模板字符串。这可能有一个很好的理由,但是当编码时,将字符串文字字符从引号或双引号转换为回调函数以获得插值特性是很麻烦的。CoffeeScript可能不是完美的,但是使用相同的字符串文字字符(双引号)并且总是能够插入是一个很好的特性。
`This is my ${name}`
#22
4
If you're jumping back an forth between JavaScript and C#, it's best to train your fingers for the common convention which is double quotes.
如果您在JavaScript和c#之间来回跳转,最好是为通用约定训练您的手指,这是双引号。
#23
4
There is no difference between single and double quotes in JavaScript.
在JavaScript中,单引号和双引号之间没有区别。
Specification is important:
规范是重要的:
Maybe there are performance diffs, but they are absolutely minimum and can change everyday according to browsers' implementation. Further discussion is futile unless your JavaScript application is hundreds of thousands 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.
今天,在一个特定的浏览器和平台,等等。
#24
3
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 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时,使用单引号更容易,这样您就不必在属性周围转义所有双引号。
#25
3
I've been running the following about 20 times. And it appears that double quotes are about 20% faster.
我已经跑了20次了。而且双引号的速度快了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));
#26
2
After reading all the answers that say it maybe be faster or maybe have advantages, I would say double quote is better or maybe faster too because Google closure compiler convert single quotes to double quotes.
在读完所有的答案后,我认为双引号更好,或者可能更快,因为谷歌关闭编译器将单引号转换为双引号。
#27
2
If your JS source is:
如果你的JS来源是:
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>
JS allows arrays like that:
JS允许这样的数组:
var arr=['this','that'];
But if you stringify it, it will be for compatibly reason:
但是如果你把它捆起来,它会有一个相容性的原因:
JSON=["this","that"]
I'm sure this takes some time.
我相信这需要一些时间。
#28
2
Just to add my 2 cents: In working with both JS and PHP a few years back, I've become accustom to using single quotes so I can type the escape character ('\') without having to escape it as well. I usually used it when typing raw strings with file paths, etc. (http://en.wikipedia.org/wiki/String_literal#Raw_strings)
只需添加我的2美分:几年前在使用JS和PHP时,我已经习惯于使用单引号,这样我就可以键入escape字符('\'),而不需要逃离它。我通常在用文件路径键入原始字符串时使用它(http://en.wikipedia.org/wiki/String_literal#Raw_strings)。
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?". 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). 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')
.
无论如何,我的约定最终变成了在标识符类型的原始字符串上使用单引号,比如if (s == 'string')…(在其中转义字符永远不会被使用)和双引号,比如“嘿,怎么了?”我还在注释中使用单引号作为显示标识符名称的版式约定。这只是一个经验法则,我只在需要时才会中断,比如在键入HTML string '
Bottom line, and as some have mentioned/alluded to, pick a convention, stick with it, and only deviate when necessary.
底线,正如一些人提到的,选择一个惯例,坚持它,并且只在必要时偏离。
#29
2
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. The same is when you create javascript with PHP.
您可以使用单引号或双引号。这使您能够轻松地在HTML属性内嵌套javascript,而无需转义引号。在使用PHP创建javascript时也是如此。
The general idea is: if it is possible use such quotes that you won't need to escape. Less escaping = better code.
一般的想法是:如果有可能使用这样的引用,你就不需要逃避。更少的转义=更好的代码。
#30
1
There is strictly no difference, so it is mostly a matter of taste and of what is in the string (or if the JS code itself is in a string), to keep number of escapes low.
严格来说没有区别,所以这主要是一个味道和字符串(或者如果JS代码本身是字符串)的问题,以保持低的溢出。
The speed difference legend might come from PHP world, where the two quotes have different behavior.
速度差异的传说可能来自于PHP世界,在这里,这两个引用有不同的行为。