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
4 Answers
Reset to default 7It'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条)