JavaScript语法:语法禁止索引对象文字? [英] JavaScript grammar: indexing object literals syntactically forbidden?

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

问题描述

在Chrome 63.0和Firefox 58.0中,似乎向对象文字添加索引会阻止将该对象解析为对象.

In Chrome 63.0 and Firefox 58.0, it appears that adding an index to an object literal prevents the object from being parsed as an object.

{"a":"b"}
17:37:32.246 {a: "b"}

{"a":"b"}["a"]
17:37:36.578 VM288:1 Uncaught SyntaxError: Unexpected token :

有人可以解释为什么解析器不按我的方式解析吗? (我认为规范的实现中肯定有一个错误……)似乎认为这不是在解析对象.

Can anybody explain why the parser doesn't parse this the way I do? (I think there must be a bug in my implementation of the spec...) It seems to think it's not parsing an object.

将对象括在方括号中会产生语法正确的表达式:

Surrounding the object in brackets results in syntactically correct expression:

({"a":"b"})["a"]
17:42:03.993 "b"

推荐答案

它与控制台将{}评估为 block 而不是对象文字有关. >.

It has to do with the console evaluating the {} as a block instead of an object literal.

此问题类似于在控制台中定义JavaScript对象" 有关StackOverflow的问题.

This question is similar to "Defining a JavaScript object in console" and "Is the curly brackets object notation valid in any expression?" question on StackOverflow.

规范中的关键部分:

ExpressionStatement:[lookahead∉{{function}] Expression ;

ExpressionStatement: [lookahead ∉ {{, function}] Expression ;

注意: ExpressionStatement 不能以开头的卷曲开始 大括号,因为它可能与 Block 模棱两可.还有, ExpressionStatement 不能以function关键字开头,因为 可能会与 FunctionDeclaration 混淆.

NOTE: An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

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

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