Luk*_*uke 2 javascript string dictionary key object
到目前为止,在我看到的所有教程中,字典中的项目都已初始化,如下所示:
var myObj = { foo:"bar", fooBar:"fooBaz" };
Run Code Online (Sandbox Code Playgroud)
为什么键没有被引用?它们不只是字符串吗?
如果我想在字典键中包含空格,我该怎么办?
当键是正确的标识符或数字时,引号是可选的。对于其他键,需要引号:
var foo = {
identifier: "no quotes",
"@balloonz are pretty": "quotes necessary"
};
Run Code Online (Sandbox Code Playgroud)
必须使用运算符访问不是标识符的属性名称[ ]:
if (foo["@balloonz are pretty"] != null) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
[ ]通过和访问属性的语义.是相同的;这只是语法上的区别。
if (foo.identifier != null) {
// ...
}
Run Code Online (Sandbox Code Playgroud)