问题
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