简体   繁体   English

JavaScript语法:for / for-in循环规则?

[英]JavaScript Grammar: for/for-in loop rules?

I am writing a JavaScript parser, but the grammar rules for for loops is a bit confusing. 我正在编写JavaScript解析器,但是for循环的语法规则有点令人困惑。 From the specs : 从规格

'for' LPAREN (
    (expressionNoln)? SEMI (expression)? SEMI (expression)? RPAREN statement
    | 'var' variableDeclarationListNoln SEMI (expression)? SEMI (expression)? RPAREN statement
    | leftHandSideExpression 'in' expression RPAREN statement
    | 'var' variableDeclarationNoln 'in' expression RPAREN statement
    )

I'm trying to figure out what the difference between expressionNoln and just a regular expression . 我试图找出expressionNoln和正则expression之间的区别。 And, in the process, figure out what's going on with variableDeclartionNoln and variableDeclartionListNoln . 并且,在此过程中,找出variableDeclartionNolnvariableDeclartionListNoln发生了什么。

The only difference I've found is a bit further down, between relationalExpression and relationalExpressionNoln . 我发现的唯一区别是在relationalExpressionrelationalExpressionNoln之间还差一点。 The latter rule is missing the in operator. 后一个规则缺少in运算符。

Did I get that right, or am I just confused? 我说对了,还是我感到困惑?

You are correct. 你是对的。 I think you are confused because the ANTLR grammar has the identifier misspelled. 我认为您很困惑,因为ANTLR语法的标识符拼写错误。 It should be variableDeclarationListNoIn for "no in". 对于“ no in”,应为variableDeclarationListNoIn ANTLR spells it Noln using an lowercase l instead of an uppercase I . ANTLR使用小写l而不是大写I拼写Noln

Removing the in from the expression is important to avoid an ambiguity for the special use of the in in the for statement. 从表达式中删除in对于避免for语句in in的特殊用法产生歧义很重要。

BTW, your question implies that the link you give is the specification. 顺便说一句,您的问题暗示您提供的链接是规范。 It is not. 它不是。 It is a link to an example ANTLR grammar. 它是到ANTLR语法示例的链接。 The official standard can be found here: http://www.ecma-international.org/publications/standards/Ecma-262.htm 可以在以下位置找到官方标准: http : //www.ecma-international.org/publications/standards/Ecma-262.htm

I imagine each line represents the following for s: 我想每一行代表以下for S:

for (i = 0; i < 10; i++) console.log(i);
for (var i = 0; i < 10; i++) console.log(i);
for (i in obj) console.log(i + ': ' + obj[i]);
for (var i in obj) console.log(i + ': ' + obj[i]);

I'm not sure what No Line (which is what I imagine it stands for) means though. 我不知道什么No Line (这是我想象它代表什么),是指虽然。

SEMI = ';'    LPAREN = '('    RPAREN = ')'     ? = optional      | = or

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM