What is the behavior of typing {a:1} giving 1, and {a:1, b:2} giving an error in a Javascript console?

StackOverflow https://stackoverflow.com/questions/3731802

문제

The following will show in Firebug or in jsconsole.com or in other Javascript interactive console:

>>> foo = { a : 1, b : 2.2 }
Object { a=1, more...}

>>> foo.a
1

>>> foo.b
2.2

>>> { a : 1, b : 2.2 }
SyntaxError: invalid label { message="invalid label", more...}

>>> { a : 1 }
1

why is the 1 returning for {a : 1} and why is {a : 1, b : 2.2} giving an error? In Ruby, they would come back the same way you defined it.

도움이 되었습니까?

해결책

The second line is giving you a SyntaxError because the { token at the beginning of it causes an ambiguity, the parser treats it as if it were a Block statement, not the start of an object literal.

For example, a valid Block statement:

{ foo: 'bar' }

The above looks like an object literal, but it isn't, because the code is evaluated in statement context.

It will be parsed as a Block, that contains a labelled statement (foo), followed by an expression statement ('bar').

To ensure that you are using the grammar of an object literal, you can wrap it with parentheses (also known as the grouping operator):

({ foo: 'bar' })

The grouping operator can only take Expressions, therefore there is no ambiguity.

See also:

다른 팁

I'm not 100% positive, but what I think is happening is that in the second line you're defining a block, not an object. Thus the parse error comes when the parser reaches the comma, since it expects a semi color. The labels defned are labels, like in a goto or switch statement. I hope this explanation makes any sense.

console do as eval('you input')

eval({....}) --- this will get an error
eval('({....})')---eval string as a function
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top