最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

The following will show in Firebug or in jsconsole 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 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.

Share Improve this question edited Sep 17, 2010 at 0:20 nonopolarity asked Sep 17, 2010 at 0:08 nonopolaritynonopolarity 151k142 gold badges489 silver badges781 bronze badges 2
  • 1 This is a great question followed by a terrific answer! Obviously I'm talking about CMS's answer. – Marcus Stade Commented Sep 17, 2010 at 0:28
  • stackoverflow.com/questions/1509535/javascript-false-and-false/… is a seemingly irrelevant question, but with a relevant answer to one thing you may be tripping on. – Crescent Fresh Commented Sep 17, 2010 at 0:31
Add a comment  | 

3 Answers 3

Reset to default 25

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:

  • Why the open quote and bracket for eval('(' + jsonString+ ')') when parsing json string

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论