Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我已经看到以下两种在 javascript 中为对象文字指定属性的方法。
var a = {prop:2}
和
var a ={'prop':2}
这两种方式有什么区别。我知道第二种方法允许我们在属性名称中包含空格。还有其他优势吗?
除了您观察到创建不是有效标识符的属性名称的能力之外,没有任何区别。通过使用带引号的字符串作为属性名称,可以使用任何字符串。当然,在访问此类属性时,您以后必须使用[ ]而不是.:
[ ]
.
var obj = { 'crazy property name': 100 }; if (obj[ 'crazy property name' ] > 1) alert("hi");
请注意,严格的 JSON 语法要求引用属性名称,而且它要求始终使用双引号字符进行引用。