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

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

programmeradmin4浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论