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 workit 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; //worksI 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:访问名称以数字开头的对象属性
发布评论