Javascript中的'',""和没有引号是什么意思?

exp*_*nja 7 javascript quotes evaluation double-quotes

我意识到我一直在他们之间切换而不理解为什么,并且我发现很难搜索.

Ja͢*_*͢ck 16

' '并且" "是一样的; 它们用于定义字符串文字.

没有引号的东西可以是标识符,关键字,非字符串文字,属性名称或数字(可能错过了一个).

例子:

"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)
Run Code Online (Sandbox Code Playgroud)

用单引号括起来的字符串文字不需要转义双引号,反之亦然,例如:

'<a href="">click me</a>'    HTML containing double quotes
"It's going to rain"         String containing single quote
Run Code Online (Sandbox Code Playgroud)

  • 最后两个不会被认为是标识符,是吗?在我看来,它们是各自类型(数字和正则表达式)的字面语法,就像前两个字符串示例一样. (3认同)

Rah*_*hul 6

' '" "用于引用字符串文字并表示字符串,而不带引号的字面值是变量(变量名称,常量),称为标识符,示例

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


var = "Ho There"
Run Code Online (Sandbox Code Playgroud)

你可能会质疑,' (single quote)和之间有什么区别" (Double quote)

区别在于,"如果有特殊字符,那么它们需要转义.例:

变量="hi"那里"; --->这里你需要逃避"内部字符串之类的

Variable = "hi \" there"; 
Run Code Online (Sandbox Code Playgroud)

但是如果使用,'则不需要转义(除非'字符串中有额外的).你可以喜欢

var = 'Hello " World"';
Run Code Online (Sandbox Code Playgroud)


dje*_*lin 5

"并且'可以互换(但需要一起使用).

myObject["property"]并且myObject.property也可以互换. $var foo = "property"; myObject[foo](以下评论).