Why is a bare Array valid Javascript syntax, but not a bare object? - Stack Overflow

In my Javascript console (in Chrome) I'm trying this:{ 'a' : 1 }and getting SyntaxError:

In my Javascript console (in Chrome) I'm trying this:

 { 'a' : 1 }

and getting SyntaxError: Unexpected token :

But this works:

 ['a', 1]

What gives???

In my Javascript console (in Chrome) I'm trying this:

 { 'a' : 1 }

and getting SyntaxError: Unexpected token :

But this works:

 ['a', 1]

What gives???

Share Improve this question asked Jun 29, 2013 at 15:59 Alex DAlex D 30.5k7 gold badges84 silver badges131 bronze badges 1
  • Thanks to everybody for explaining... though I still consider this to be a defect in JavaScript. The places where a block can appear in the text of a valid JS program are pletely different from the places where an object literal can appear, and the parser should easily be able to tell the difference. – Alex D Commented Jun 29, 2013 at 18:10
Add a ment  | 

4 Answers 4

Reset to default 7

It's because curly braces have two uses - either introducing a block, or as the start of an object literal (the latter being an expression).

The console can't tell which, so it assumes a statement block, and only later finds that the contents of the block can't be parsed as statements.

For array literals with square brackets that ambiguity doesn't exist.

The ambiguity can be resolved by changing the context so that the {...} must be interpreted as an expression rather than a statement block, e.g. by making it the RHS of an operator, wrapping it in parentheses, or passing it as a function parameter, etc.

This is a block:

{
    var x = 'stuff'
    function doStuff(arg) { alert(arg) }
    doStuff(x)
}

It will alert stuff.

Now, about your example: JavaScript thinks it's a block, like this:

{
    'a' : 1
}

Since 'a' : 1 is not a valid statement, it fails.

Note that if you do

'x' + { 'a' : 1 }

It works, because there's no way a block could e after a +.

As others have pointed out, this is due to the fact that curly braces have dual use.

The easiest way to work around the ambiguity is by adding a pair of parentheses:

> {'a': 1}
SyntaxError: Unexpected token :

> ({'a': 1})
Object {a: 1}

You can do new Object({'a' : 1}) for that.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745654916a4638485.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信