为什么裸阵列有效的Javascript语法,但不是裸对象? [英] Why is a bare Array valid Javascript syntax, but not a bare object?

查看:75
本文介绍了为什么裸阵列有效的Javascript语法,但不是裸对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Javascript控制台(在Chrome中)我正在尝试这个:

In my Javascript console (in Chrome) I'm trying this:

 { 'a' : 1 }

并且获得 SyntaxError:意外的令牌:

但这样可行:

 ['a', 1]

什么给出???

推荐答案

这是因为花括号有两个用途 - 要么引入一个块,要么作为对象文字的开头(后者是表达式)。

It'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.

可以通过更改上下文来解决歧义,以便 {...} 必须被解释为表达式而不是语句块,例如通过使其成为运算符的RHS,将其包装在括号中,或将其作为函数参数传递等。

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.

这篇关于为什么裸阵列有效的Javascript语法,但不是裸对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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