admin管理员组文章数量:1202392
The following code produces a syntax error in Chrome and Firefox, but not Node.js:
{"hello": 1}
However, the following code works everywhere:
var x = {"hello": 1}
Also, the following works everywhere:
{hello: 1}
What is the explanation for this strange behavior?
The following code produces a syntax error in Chrome and Firefox, but not Node.js:
{"hello": 1}
However, the following code works everywhere:
var x = {"hello": 1}
Also, the following works everywhere:
{hello: 1}
What is the explanation for this strange behavior?
Share Improve this question edited Dec 31, 2024 at 9:44 dumbass 27.2k4 gold badges36 silver badges73 bronze badges asked Jun 25, 2013 at 13:39 ipartolaipartola 1,6463 gold badges15 silver badges25 bronze badges 02 Answers
Reset to default 17The NodeJS REPL evaluates code as an expression, by wrapping the code in parentheses, causing {"hello":1}
to be ({"hello":1})
which is parsed successfully as an object literal.
Usually and elsewhere (in Chrome/Firefox's console), the curly braces are parsed as the delimiters of a block, like:
/*imagine if (true) */ {
"hello": 1 // <-- What's this syntax? It's meaningless.
}
{hello:1}
parses successfully, because hello
in this context has the meaning of a label:
/*imagine if (true) */ {
hello: 1;
} // ^-- Automatic Semicolon Insertion
The first example is not an object literal, it is a block. Blocks contain statements. The squence String literal, colon, Number literal is not a valid statement.
The second example is an object literal.
The third example is also a block, but you have replaced the string literal and colon with a label (which is allowed, but is pointless as there is no loop).
Context is important in JavaScript.
本文标签:
版权声明:本文标题:javascript - Why can an object literal trigger a syntax error in some engine REPLs, but not in others? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738562371a2099483.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论