是否有不同的获取此属性的方法,或者我应该不使用以一个数字?
Is there a different way to get this property, or should I just not use a key that starts with a number?
推荐答案您可以使用以下语法执行使用括号表示法所描述的内容:
You can use the following syntax to do what you describe using bracket notation:
myObject["myProperty"]括号表示法与点表示法(例如 myObject.myProperty )的不同之处在于它可用于访问属性谁的名字是非法的。非法意味着使用点表示法,您仅限于使用字母数字的属性名称(加上下划线 _ 和美元符号 $ ),不要以数字开头。括号表示法允许我们使用字符串来访问属性并绕过它。
Bracket notation differs from dot notation (e.g. myObject.myProperty) in that it can be used to access properties whose names are illegal. Illegal meaning that with dot notation, you're limited to using property names that are alphanumeric (plus the underscore _ and dollar sign $), and don't begin with a number. Bracket notation allows us to use a string to access a property and bypass this.
myObject.1 // fails, properties cannot begin with numbers myObject.& // fails, properties must be alphanumeric (or $ or _) myObject["1"] // succeeds myObject["&"] // succeeds这也意味着我们可以使用字符串变量来查找和设置对象的属性:
This also means we can use string variables to look up and set properties on objects:
var myEdgyPropertyName = "||~~(_o__o_)~~||"; myEdgyObject[myEdgyPropertyName] = "who's there?"; myEdgyObject[myEdgyPropertyName] // "who's there?";您可以阅读有关点和括号表示法的更多信息此处,在MDN上。
You can read more about dot and bracket notation here, on MDN.
更多推荐
我可以获得以数字开头的javascript对象属性名称吗?
发布评论