2012-03-23 13 views
3

可能性の重複:for(;;){…}
Empty for loop - for(;;)なぜ(;;){...}は無限ループですか?

私はちょうど(L1045で)UglifyJSのJSパーサで奇妙な構造を発見しました。

空の条件がundefinedに解決され、ブール値falseに変換されると仮定しました。しかし、そうは間違いありません。

明らかに、無限ループを引き起こします。私はこの振る舞いを再現することができましたが、私は理由を知りません。任意の(論理的な)説明?

その他:これが可能な場合、なぜwhile(){…}は機能しませんか?

答えて

4

これは、セマンティクスの定義に過ぎません。欠落している「テスト」式は、値がtrueの式として処理されます。言語は人によって構成されており、好きな振る舞いを自由に指定することができます。明らかに、その挙動は

+3

ここにはその仕様があります:http://es5.github.com/x12.html#x12.6.3 –

+0

何かの理由で、私のためにロードするのは永遠に取っておかれました:-) – Pointy

+0

** + 1 * Mr. Eich ... :) – gdoron

4

for(;;){…} :-)氏アイヒが好きなものは有効と見なされていないtruewhile(){}として空の条件が解釈です。前に述べたように、言語に完全に依存していますが、仕様に記述されています。

1

ECMA-262 language specification of JavaScript(セクション12.6.3)では、forループの動作をどのようにするべきかが定義されています。

セミコロンの前後の情報が利用できない場合、ループを終了する条件がないことが定義からわかります。ループを終了する唯一の方法は、テスト条件とオプションで開始値とステップ値を定義することです。

動作が異なる方法で定義されている可能性がありますが、それはそれだけではありません。

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. 

要旨は:最初の式は「falsey」の値を返したときに文に停止します。

式がない場合はfalseを返さないため、スクリプトは永遠に(またはループ本体の内部から文が実行されるまでbreakまで)実行されます。

関連する問題