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

编程入门 行业动态 更新时间:2024-10-25 16:17:39
本文介绍了我可以获得以数字开头的javascript对象属性名称吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 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?

推荐答案

您可以使用以下语法执行使用括号表示法所描述的内容:

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对象属性名称吗?

本文发布于:2023-11-06 05:26:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562819.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以获得   开头   属性   对象   名称

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!