这很有效.
var a = 'ontouchstart' in window; for (;;) { console.log(a); break; }
这会导致语法错误.为什么?
for (var a = 'ontouchstart' in window;;) { console.log(a); break; }
这很有效.
for (var a = ('ontouchstart' in window);;) { console.log(a); break; }
解决方法
This causes Syntax error. Why?
避免与for-in-loops混淆. syntax specification for for-loops是明确的:
IterationStatement : for ( ExpressionNoIn
opt
; Expression
opt
; Expression
opt
) Statement
IterationStatement : for ( var VariableDeclarationListNoIn ; Expression
opt
; Expression
opt
) Statement
这个NoIn后缀通过整个语法语法传播,并在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.
但是,我不明白为什么在正常的for循环中使用NoIn变体 – 它们在制作中是合理的.我猜这是为了避免程序员混淆并简化解析器.