我剛剛發現UglifyJS的JS解析器一個奇怪的結構(在L1045):for(;;){…}
。
我認爲一個空的條件會解析爲undefined
,它被轉換爲布爾值false
。但事實絕非如此。
顯然,它會觸發一個無限循環。我能夠重現這種行爲,但我不知道爲什麼。任何(邏輯)解釋?
此外:當這是可能的,爲什麼不while(){…}
工作?
我剛剛發現UglifyJS的JS解析器一個奇怪的結構(在L1045):for(;;){…}
。
我認爲一個空的條件會解析爲undefined
,它被轉換爲布爾值false
。但事實絕非如此。
顯然,它會觸發一個無限循環。我能夠重現這種行爲,但我不知道爲什麼。任何(邏輯)解釋?
此外:當這是可能的,爲什麼不while(){…}
工作?
這只是語義的定義。將缺少的「測試」表達式視爲值爲true
的表達式。語言由人組成,他們可以隨意指定他們喜歡的任何行爲。很顯然,這種行爲是值得艾希先生喜歡:-)
for(;;){…}
解譯空狀態作爲true
和while(){}
不被視爲有效。如前所述,它完全依賴於語言,但在說明書中進行了描述。
在ECMA-262 language specification of JavaScript(第12.6.3節)中定義了for循環的行爲應如何。
從定義中可以看出,如果分號周圍和分號之間的信息不可用,則沒有條件離開循環。離開循環的唯一方法是定義一個測試條件以及可選的一些開始和步驟值。
行爲可以用不同的方式定義,但這不是它是如何定義的。
來自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語句當一個表達式返回 「falsey」 值停止。由於沒有表達式不返回false,腳本將永遠運行(或直到break
語句從循環體內執行)。
下面是關於此的規範:http://es5.github.com/x12.html#x12.6.3 – 2012-03-23 12:27:31
哦,謝謝它永久加載我,出於某種原因:-) – Pointy 2012-03-23 12:29:16
** + 1 * Eich先生...... :) – gdoron 2012-03-23 12:29:16