简体   繁体   English

访问JavaScript Object Literal

[英]Accessing JavaScript Object Literal

Maybe is just a stupid question, but, I would appreciate having an explanation of the following behavior: 也许只是一个愚蠢的问题,但是,我希望能解释以下行为:

var obj = {
    key : "val1",
    123 : "val2"
};

obj.key; // "val1"
obj.123; // Syntax error: missing; before statement
obj[123]; // "val2"

Why obj.key is different from obj.123 although they have been declared both as keys of obj . 为什么obj.keyobj.123不同,尽管它们都被声明为obj键。


Accessing the object literal in this way obj.123 is wrong. 以这种方式访问​​对象文字obj.123是错误的。

And declaring the object in the following way is correct? 并以下列方式声明对象是正确的吗? The browsers I have tested are IE9, firefox and chrome and for all of them it works fine. 我测试过的浏览器是IE9,firefox和chrome,对于所有这些浏览器都运行良好。

var obj = {
    123 : "val1"
};

JavaScript will let you use just about any string as an object property name, but when accessing properties with the dot notation you're only supposed to use property names that would be valid JS identifiers - which have to start with a letter, the underscore or a dollar sign. JavaScript将允许您使用任何字符串作为对象属性名称,但是当使用点表示法访问属性时,您应该只使用属于有效JS标识符的属性名称 - 必须以字母,下划线或一个美元符号。 So for property names that don't meet the rules for valid identifiers you have to access them with the bracket notation. 因此,对于不符合有效标识符规则的属性名称,您必须使用括号表示法访问它们。

Although the bracket notation works with a number, behind the scenes JS will convert that number to a string. 尽管括号表示法使用数字,但在幕后,JS会将该数字转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM