以下代码在Chrome和Firefox中产生语法错误,但不会在Node.js中产生语法错误:
- {"hello": 1}
但是,以下代码无处不在:
- var x = {"hello": 1}
此外,以下作品无处不在:
- {hello: 1}
这个奇怪的行为有什么解释?
解决方法
NodeJS REPL evaluates code as an expression通过将代码包含在括号中,导致{“hello”:1}成为({“hello”:1}),它被成功解析为对象字面值.
通常和其他地方(在Chrome / Firefox的控制台中),大括号被解析为块的分隔符,如:
- /*imagine if (true) */ {
- "hello": 1 // <-- What's this Syntax? It's meaningless.
- }
{hello:1}成功解析,因为这个上下文中的hello有一个label的含义:
- /*imagine if (true) */ {
- hello: 1;
- } // ^-- Automatic Semicolon Insertion