Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...