如何访问数字属性? [英] How to access a numeric property?
问题描述
我有一个像这样的对象:
I have an object like:
var myObject = { '0' : 'blue' };
现在,当我尝试访问键'0'的值时:
Now, when I try to access the value of the key '0' like:
myObject.0
...我收到了一个错误。 (也许这不是正确的方法?)
...I am getting an error. (Maybe this is not the proper way?)
如何访问数字键的值(如上所述)?
How can I access the value of a key that is a number (like the above)?
推荐答案
这应该有效:
myObject["0"]
( myObject [propertyName]
是 myObject.propertyName
的替代语法。)
您收到错误是因为,在JavaScript中,标识符不能以数字开头。来自变量页面developer.mozilla.org/rel =noreferrer> Mozilla开发人员中心:
You're getting the error because, in JavaScript, identifiers can't begin with a numeral. From the Variables page at the Mozilla Developer Centre:
JavaScript标识符必须以$ b开头$ b带字母,下划线(_)或
美元符号($);后续字符
也可以是数字(0-9)。因为
JavaScript区分大小写,所以字母
包括字符A到Z
(大写)和字符a
到z(小写)。
A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).
这篇关于如何访问数字属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!