JavaScript grammar: indexing object literals syntactically forbidden?

爷,独闯天下 提交于 2019-12-11 05:33:10

问题


In Chrome 63.0 and Firefox 58.0, it appears that adding an index to an object literal prevents the object from being parsed as an object.

{"a":"b"}
17:37:32.246 {a: "b"}

{"a":"b"}["a"]
17:37:36.578 VM288:1 Uncaught SyntaxError: Unexpected token :

Can anybody explain why the parser doesn't parse this the way I do? (I think there must be a bug in my implementation of the spec...) It seems to think it's not parsing an object.

Surrounding the object in brackets results in syntactically correct expression:

({"a":"b"})["a"]
17:42:03.993 "b"

回答1:


It has to do with the console evaluating the {} as a block instead of an object literal.

This question is similar to "Defining a JavaScript object in console" and "Is the curly brackets object notation valid in any expression?" question on StackOverflow.

The key part from the spec is:

ExpressionStatement: [lookahead ∉ {{, function}] Expression ;

NOTE: An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.




回答2:


{"a":"b"}["a"] - {} is detected as bracket body or block - not an object. Lets look an example on if statement, you can have something like this

if(condition) {
   "a": "b"
}

So actually you get an statement like "a" : "b" which is invalid.

({"a":"b"})["a"] - () evaluates the expression inside it, so {} is detected as object



来源:https://stackoverflow.com/questions/48548444/javascript-grammar-indexing-object-literals-syntactically-forbidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!