问题描述
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };
这个例子中的 car.manyCars.a
和 car.manyCars.b
有什么区别?
What's the difference between car.manyCars.a
and car.manyCars.b
in this example?
推荐答案
无.
引号允许您指定不是有效 javascript 标识符的名称,但 a
和 b
都是.例如,这不合法:
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" };
而这是
var car = { "a*b": "Saab" };
因为 a*b 不是一个有效的标识符.
As a*b is not a valid identifier.
请注意,JSON(基于 JavaScript)不允许使用不带引号的名称.
Note that JSON (which is based on JavaScript) does not allow unquoted names.
编辑
这里有一个例外,正如您所注意到的,您可以使用数字而不引用它们,它们不是有效的 javascript 标识符.这实际上很奇怪,没有充分的理由,可能是简写声明的机会.car.7
不会因为同样的原因解析,它不是一个有效的标识符,你需要使用 car[7]
.
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]
.
这篇关于在 JavaScript 中,双引号(“")和不带双引号的属性名称有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!