Why does 'in window' in for loop initialization cause syntax error?

This works.

var a = 'ontouchstart' in window;
for (;;) {
  console.log(a);
  break;
}

This causes syntax error. Why?

for (var a = 'ontouchstart' in window;;) {
  console.log(a);
  break;
}

This works.

for (var a = ('ontouchstart' in window);;) {
  console.log(a);
  break;
}

This causes syntax error. Why?

To avoid confusion with for-in-loops. The syntax specification for for-loops is explicit:

IterationStatement : for ( ExpressionNoIn opt ; Expression opt ; Expression opt ) Statement

IterationStatement : for ( var VariableDeclarationListNoIn ; Expression opt ; Expression opt ) Statement

This NoIn suffix spreads through the whole syntactic grammar, and ends in the 11.8 Relational Operators (Syntax) section:

RelationalExpression :

ShiftExpression
RelationalExpression < ShiftExpression
RelationalExpression > ShiftExpression
RelationalExpression <= ShiftExpression
RelationalExpression >= ShiftExpression
RelationalExpression instanceof ShiftExpression
RelationalExpression in ShiftExpression

RelationalExpressionNoIn :

ShiftExpression
RelationalExpressionNoIn < ShiftExpression
RelationalExpressionNoIn > ShiftExpression
RelationalExpressionNoIn <= ShiftExpression
RelationalExpressionNoIn >= ShiftExpression
RelationalExpressionNoIn instanceof ShiftExpression

NOTE: The NoIn variants are needed to avoid confusing the in operator in a relational expression with the in operator in a for statement.

However, I don't understand myself why the NoIn variants are used in the normal for-loop - they are reasonable in for-in-productions. I'd guess it's to avoid confusion of the programmer and to simplify parsers.

链接地址: http://www.djcxy.com/p/68888.html

上一篇: Rails路由与查询参数

下一篇: 为什么'for window'中的for循环初始化会导致语法错误?