开发者

In JavaScript, what is the difference between a property name in double-quotes ("") and without? [duplicate]

This question already has answers here: What is the difference between object keys with quotes and without quotes? 开发者_如何转开发 (5 answers) Closed 5 years ago.
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };  

What's the difference between car.manyCars.a and car.manyCars.b in this example?


None whatsoever.

Quotes allow you to specify names which are not valid javascript identifiers, but both a and b are. For example, this wouldn't be legal:

var car = { a*b: "Saab" };

whereas this would be

var car = { "a*b": "Saab" };

As a*b is not a valid identifier.

Note that JSON (which is based on JavaScript) does not allow unquoted names.

Edit
An exception here, as you've noticed, you can use numbers without quoting them, which are not valid javascript identifiers. This is actually rather weird, don't have a good reason for this, probably the opportunity to shorthand the declaration. car.7 won't parse for the same reason, it is not a valid identifier, and you need to use car[7].


As roe said, there's no difference in the end, but it allows to you to use otherwise reserved keywords or invalid identifiers:

var x = { 'a b c' : 1, 'a%#!6!#' : 1};

It probably isn't a bad idea to always use quotes. Different javascript engines consider different things to be reserved. For example, this works fine in a browser, but causes a syntax error in Rhino:

var x = { native : true };

The Mozilla Developer Network has some good information too: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators

Dot notation

some_object.property

property must be a valid JavaScript identifier, i.e. a sequence of alphanumerical characters, also including the underscore ("_") and dollar sign ("$"), that cannot start with a number. For example, object.$1 is valid, while object.1 is not.

Bracket notation

some_object[property]

property is a string. The string does not have to be a valid identifier; it can have any value, e.g. "1foo", "!bar!", or even " " (a space).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜