我可以获得以数字开头的 javascript 对象属性名称吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5809790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:25:50  来源:igfitidea点击:

Can I get a javascript object property name that starts with a number?

javascriptkey

提问by bodine

var myObj = {"suppliers":[{"name":"supplier1","12m":"0.08","24m":"0.06"}]};

alert(myObj.suppliers[0].12m);

Is there a different way to get this property, or should I just not use a key that starts with a number?

有没有不同的方法来获得这个属性,还是我不应该使用以数字开头的键?

回答by mattsven

You can use the following syntax to do what you describe using bracket notation:

您可以使用以下语法来执行您使用括号表示法描述的操作:

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.myProperty)的不同之处在于它可用于访问名称非法的属性。非法意味着使用点表示法,您只能使用字母数字(加上下划线_和美元符号$)的属性名称,并且不能以数字开头。括号表示法允许我们使用字符串来访问属性并绕过它。

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?";

You can read more about dot and bracket notation here, on MDN.

您可以在 MDN 上阅读有关点和括号表示法的更多信息。

回答by cmd

Yes, use bracket syntax:

是的,使用括号语法:

alert(myObj.suppliers[0]["12m"]);

alert(myObj.suppliers[0]["12m"]);

From MDN

来自MDN

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).

JavaScript 标识符必须以字母、下划线 (_) 或美元符号 ($) 开头;后续字符也可以是数字 (0-9)。因为 JavaScript 区分大小写,所以字母包括字符“A”到“Z”(大写)和字符“a”到“z”(小写)。