Javascript:访问名称以数字开头的对象属性

编程入门 行业动态 更新时间:2024-10-25 06:22:42
本文介绍了Javascript:访问名称以数字开头的对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在创建一个 Javascript / jQuery 应用程序。 我需要处理 JSON 响应代表 HashMap ,如下所示:

{accounts:{MediaFire:{provider:MediaFire,usedStorage:779680,totalStorage :53687091200},4Sync:{provider:4Sync,usedStorage:620692,totalStorage :16106127360} } }

I使用一个pasing函数(这是我无法控制的),它在一个对象 result 中返回解析的JSON响应。

var usedStorage = result.accounts.4Sync.usedStorage; //不起作用

它不起作用,我认为是因为 ...与其他对象的相同操作正常工作:

var usedStorage = result.accounts.MediaFire.usedStorage; //作品

我知道结果对象包含对象 4Sync ,但我无法访问它。以下是Chrome控制台的屏幕截图:

有没有解决方法可以解决这个问题?

解决方案

使用方括号:

var usedStorage = result.accounts [4Sync]。usedStorage;

属性标识符可以以数字开头,但成员表达式可以以。字符只会允许有效的变量标识符(因为其他的都是不明确的)。为了解决这个问题,你可以使用方括号语法,它是等价的,但允许使用任何字符串。

如果你有兴趣,这里是语法:

MemberExpression :结果, PrimaryExpression 结果, FunctionExpression MemberExpression [ 表达式 ] MemberExpression 。 IdentifierName

注意方括号可以包含任何表达式,但是。后面只能跟一个标识符名称(基本上,任何有效的标识符,以及ES5中的保留字)。

I'm creating a Javascript / jQuery application.

I need to process a JSON response that represents a HashMap, like this:

{ "accounts": { "MediaFire": { "provider": "MediaFire", "usedStorage": "779680", "totalStorage": "53687091200" }, "4Sync": { "provider": "4Sync", "usedStorage": "620692", "totalStorage": "16106127360" } } }

I use a pasing function (which I can't control), which returns the parsed JSON response in an object result.

When I try to access the 4Sync like this:

var usedStorage = result.accounts.4Sync.usedStorage; //doesn't work

it doesn't work, I think it's because of the 4 at the beginning... The same operation with the other object works fine:

var usedStorage = result.accounts.MediaFire.usedStorage; //works

I know the result object contains the object 4Sync, but I can't access it. Here is a screenshot of Chrome's console:

Is there any workaround to solve this?

解决方案

Use square brackets:

var usedStorage = result.accounts["4Sync"].usedStorage;

Property identifers can begin with a number, but member expressions with the . character will only allow valid variable identifiers (since anything else is ambiguous). To get around this, you can use the square bracket syntax, which is equivalent but allows the use of any string.

If you're interested, here is the grammar:

MemberExpression : PrimaryExpression FunctionExpression MemberExpression [ Expression ] MemberExpression . IdentifierName

Notice how square brackets can contain any expression, but the . can only be followed by an IdentifierName (basically, any valid identifier, plus reserved words in ES5).

更多推荐

Javascript:访问名称以数字开头的对象属性

本文发布于:2023-11-06 05:24:12,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:开头   属性   对象   名称   数字

发布评论

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

>www.elefans.com

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