为什么(;;){...}是一个无限循环?

时间:2012-03-23 12:22:31

标签: javascript

  

可能重复:
  Empty for loop - for(;;)

我刚刚在UglifyJS的JS解析器中找到了一个奇怪的构造(L1045):for(;;){…}

我假设空条件将解析为undefined,它将转换为布尔值false。但事实并非如此。

显然,它会触发无限循环。我能够重现这种行为,但我不知道为什么。任何(逻辑)解释?

此外:如果可能,为什么while(){…}不起作用?

4 个答案:

答案 0 :(得分:4)

这只是语义的定义。缺少“test”表达式被视为值为true的表达式。语言由人组成,他们可以自由地指定他们喜欢的任何行为。显然,这种行为是Eich先生所喜欢的: - )

答案 1 :(得分:4)

for(;;){…}将空条件解释为truewhile(){}不被视为有效。如前所述,它完全取决于语言,但在规范中有所描述。

答案 2 :(得分:1)

ECMA-262 language specification of JavaScript(第12.6.3节)中,定义了for循环的行为应该如何。

从定义中可以看出,如果分号周围和之间的信息不可用,则没有条件离开循环。离开循环的唯一方法是定义测试条件和可选的一些开始和步骤值。

行为可以用不同的方式定义,但事实并非如此。

答案 3 :(得分:1)

来自spec

12.6.3 The for Statement
    The production
        IterationStatement : for (ExpressionNoIn(opt) ; Expression(opt) ; Expression(opt)) Statement
    is evaluated as follows:
    1. If ExpressionNoIn is present, then.
        a. Let exprRef be the result of evaluating ExpressionNoIn.
        b. Call GetValue(exprRef). (This value is not used but the call may have side-effects.)
    2. Let V = empty.
    3. Repeat
        a. If the first Expression is present, then
            i. Let testExprRef be the result of evaluating the first Expression.
            ii. If ToBoolean(GetValue(testExprRef)) is false, return (normal, V, empty) .
        b. Let stmt be the result of evaluating Statement.© Ecma International 2011 91
        c. If stmt.value is not empty, let V = stmt.value
        d. If stmt.type is break and stmt.target is in the current label set, return (normal, V, empty) .
        e. If stmt.type is not continue || stmt.target is not in the current label set, then
            i. If stmt is an abrupt completion, return stmt.
        f. If the second Expression is present, then
            i. Let incExprRef be the result of evaluating the second Expression.
            ii. Call GetValue(incExprRef). (This value is not used.

此规范的要点:for语句在第一个Expression返回“falsey”值时停止。

由于缺少表达式不返回false,脚本将永远运行(或直到从循环体内执行break语句)。

相关问题