JavaScript - 使用撇号还是引号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15445539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - use apostrophes or quotation marks?
提问by Jay
For string literals, are any differences between using apostrophes or using quotes? I'm thinking in regard to performance, functionality, conventions, etc.
对于字符串文字,使用撇号或使用引号之间有什么区别吗?我在考虑性能、功能、约定等。
To clarify:
澄清:
'Hello!'
vs.
对比
"Hello!"
(for want of a more imaginative string)
(想要一个更有想象力的字符串)
采纳答案by Tucker
For me i use it depending on the contents of the string - will the string itself have double quotes or single quotes? if the string has one type of quote, i'll use the other so i don't have to escape it: e.g.:
对我来说,我根据字符串的内容使用它 - 字符串本身会有双引号还是单引号?如果字符串有一种类型的引号,我将使用另一种,所以我不必转义它:例如:
my string is: <div class="someclass" >hello</div>
我的字符串是: <div class="someclass" >hello</div>
for the above i'd use single quote so i don't have to escape the single ones:
对于上述我会使用单引号,所以我不必逃避单引号:
var str = '<div class="someclass" >hello</div>';
otherwise id need
否则需要
var str = "<div class=\"someclass\" >hello</div>";
both are perfectly valid, but ones more easy on the coder...
两者都是完全有效的,但在编码器上更容易......
回答by Vitthal
I wouldn't say there is a preferred method, you can use either. However If you are using one form of quote in the string, you might want to use the other as the literal.
我不会说有一个首选的方法,你可以使用。但是,如果您在字符串中使用一种形式的引号,您可能希望使用另一种形式作为文字。
alert('Say "Hello"');
alert("Say 'Hello'");
The most likely reason is programmer preference / API consistency.
最可能的原因是程序员偏好/API 一致性。
The difference is that you don't need to escape single quotes in double quotes, or double quotes in single quotes. That is the only difference, if you do not count the fact that you must hold the Shift key to type "
不同之处在于您不需要在双引号中转义单引号,或在单引号中转义双引号。这是唯一的区别,如果您不计算必须按住 Shift 键才能键入的事实"
回答by NINCOMPOOP
I don't think there may be any performance reason to use one or the other . Its just that sometimes you want to use double quotes inside the string so you will wrap the string in single quotes and vice versa .
我认为使用一个或另一个可能没有任何性能原因。只是有时您想在字符串内使用双引号,因此您会将字符串用单引号括起来,反之亦然。
Eg : var new = 'Abraham "Lincoln"';
Eg : var new = 'Abraham "Lincoln"';