简体   繁体   中英

curly brace in javascript

demo1:

{"aa":111}

demo2:

{aa:111}

demo1 result:

SyntaxError: Unexpected token : (in chrome)

demo2 result:

111

how to explain these two demos? tks

They're being parsed as statements, not expressions.

The { ... } is parsed as a block statement.
The aa: is parsed as a statement label.
The 111 is parsed as an expression statement containing a number. Since it's the last statement you're eval-ing, its value is returned.

The "aa": is a syntax error. Since statement labels cannot contain " s, it's parsed as an expression statement (like 111 , but a string rather than a number). Therefore, the " makes no sense.

You want them to be parsed as object literals, which are expressions.
Wrap them in parentheses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM