JavaScript对象文字语法错误 [英] JavaScript object literals syntax error

查看:117
本文介绍了JavaScript对象文字语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在Chrome和Firefox中产生语法错误,但不会产生Node.js:

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?

推荐答案

NodeJS REPL将代码评估为表达式 ,通过将代码包装在括号中,导致 {hello:1} ({hello:1})成功解析为对象文字。

The 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.

通常和其他地方(在Chrome / Firefox的控制台中),花括号被解析为块的分隔符,喜欢:

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} 成功解析,因为在此上下文中 hello 具有 label

{hello:1} parses successfully, because hello in this context has the meaning of a label:

/*imagine if (true) */ {
    hello: 1;
} //        ^-- Automatic Semicolon Insertion

这篇关于JavaScript对象文字语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆