Why does an object literal get ignored in a statement in JavaScript?

吃可爱长大的小学妹 提交于 2019-12-30 14:51:31

问题


I was messing around the JavaScript console and noticed that

>> {}[1]
[1]

evaluates as an array. After some more messing around I found that

>> b = {}[1]
undefined

gives me the expected result of undefined. At first I thought the curly braces were being interpreted as a block, but attempting

>> {a:1}[1]
[1]

still gave me the the [1] array. I would expect that if it was interpreted as a block, it would result in a syntax error. Why is this the case?

More Info: I discovered from Don't understand why you should not use an object literal at the beginning of a statement, that it likely is a block, but this does not answer how this is not a syntax error unless it is doing a lookahead to determine if it's an object literal or a block, but it's not an object literal because it's still evaluating to [1].

EDIT: I tried this in Chrome and Firefox in their debugging consoles and Node.js's command line interface.


回答1:


I would expect that if it was interpreted as a block, it would result in a syntax error. Why is this the case?

Inside a block, an expression consisting of a label followed by a number literal is valid.

but this does not answer how this is not a syntax error unless it is doing a lookahead to determine if it's an object literal or a block

It doesn't need to look ahead. It is a block because of what is on the left hand side of the { (i.e. nothing).



来源:https://stackoverflow.com/questions/45742014/why-does-an-object-literal-get-ignored-in-a-statement-in-javascript

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