What does ' ', and “ ”, and no quotes mean in Javascript?

与世无争的帅哥 提交于 2021-02-05 00:31:14

问题


I realized I've been switching between them with no understanding as to why, and am finding it hard to search for.


回答1:


' ' and " " are the same thing; they are used to define string literals.

Things without quotes can be an identifier, keyword, non-string literal, property name or a number (may have missed one).

Examples:

"hello world"        literal (string)
'hello world'        literal (string) with same contents
document             identifier (object)
{ a: 1 }             property name
if                   keyword (start conditional statement)
3.4                  literal (number)
/abc/                literal (regex object)

String literals that are enclosed in single quotes don't need escaped double quotes and visa versa, e.g.:

'<a href="">click me</a>'    HTML containing double quotes
"It's going to rain"         String containing single quote



回答2:


' ' and " " used to quote string literal and represents string(s) whereas literal without quote are variables (name of variable, constant) know as identifier, example

variable = 'Hello'; (Here `variable` is identifier and 'Hello' is string literal)


var = "Ho There"

You might question, what is the difference between ' (single quote) and " (Double quote)

Difference is ,strings within " if have special character then they need to escape. Example:

Variable = "hi " there"; ---> here you need to escape the " inside string like

Variable = "hi \" there"; 

But if using, ' then no need of escaping (unless there is a extra ' in string). You can hve like

var = 'Hello " World"';



回答3:


" and ' are interchangeable (but need to be used together).

myObject["property"] and myObject.property are also interchangeable. $var foo = "property"; myObject[foo] as well (per comment below).




回答4:


A quick jsfiddle around and both single and double quotes escape control codes etc.

In latter days I have had errors from HTML where double quotes have not been used, and if you look at the spec for JSON you'll note it is a double quote that is asked for when quoting string literals. So it is double quotes that is the convention I think, for historical reasons.

However! In these days of writing server side JS I must admit I tend to be pulled back to my C roots and double quote where I want escaped chars and single quote strings that are effectively literal chars and never likely to contain escaped chars (even though this is essentially non-productive behaviour). Besides which most of my JS is coffeescript nowadays anyway, nobody ever wrote javascript for elegance, CS is a different kettle of fish though.



来源:https://stackoverflow.com/questions/10852663/what-does-and-and-no-quotes-mean-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!