[英]Why doesn't this simple for loop work as expected?
人們可能希望以下內容打印出a
, b
, c
。
var i, rowName;
for (i = 0; i < 3; i++, rowName = ['a', 'b', 'c'][i]) {
console.log(rowName);
}
相反,它打印出undefined
, b
, c
。 為什么?
澄清:我知道如何使這項工作; 我很好奇的是為什么以上不起作用。
它打印undefined
, b
, c
的原因是因為for循環的工作方式。
for (initialization; condition; final expression)
讓我們分解你的循環。
初始化 : i = 0
條件 : i < 3
最終表達 : i++, rowName = ['a', 'b', 'c'][i]
首次輸入循環時, i
設置為0
。 這是初始化步驟。 然后檢查條件步驟i < 3
。 這在每次迭代之前完成,以決定是否繼續循環。 在每個循環之后,評估最終表達式 。 在您的示例中,在根據當前索引將rowName
設置為['a', 'b', 'c']
的元素之前增加i
。
在您的情況下,在第一次迭代中, rowName
undefined
因為尚未評估最終表達式 。 之后的每次迭代都表現得如您所期望的那樣,因為最終的表達式之前已經被評估過了。
如果你想做一個棘手的單行for循環風格,“正確”的語法是:
var array = ['a', 'b', 'c'];
for (var i = 0, rowName; rowName = array[ i++ ]; ) {
console.log(rowName);
}
注意結局;
for
循環聲明。 從技術上講,這是一個空洞的陳述;
這是你通常會做的i++
。
在這種情況下,for循環的“條件”利用了Javascript賦值運算符。 如果你有這樣的代碼:
var a;
if( a = 1 ) { // Note this is assignment = not comparison ==
console.log('true');
}
它將記錄“真”。 為什么? 因為在表達式內部, a = 1
實際上返回1
。 1
是“truthy”,意味着它在布爾上下文中像if
語句一樣求值為true。
如果您的價值是假的,則情況正好相反:
var a;
if( a = 0 ) {
console.log('true');
}
它不會記錄,因為a = 0
返回0(以及將0賦值給a
)。 0是假的。
這種糟糕的for循環語法僅適用於某些條件:
null
, undefined
, ""
等),它將過早地終止循環,因為運算符如上所述工作。 i
。 對於循環的每次迭代,它將偏離1,因為i++
在for
塊之前執行。 也就是說,你for
身體第一次執行時, i
將是1,而不是它聲明的起始值0。 我想你想要這個?
var i, rowName;
for (i = 0; i < 3; i++){
rowName = ['a', 'b', 'c'][i];
console.log(rowName);
}
你在循環的每一步重新分配rowName
,並且開始時它是undefined
。 這是你可以做的:
for(var i=0,rowName=['a','b','c'],l=rowName.length; i<l; i++){
console.log(rowName[i]);
}
或類似的東西:
var rowName = ['a', 'b', 'c'];
for(var i=0,l=rowName.length; i<l; i++){
console.log(rowName[i]);
}
真正的問題是,在滿足循環的一個test
之前for(assign; test; execute)
內部的第三個條件才會execute
。 如果test
失敗, execute
永遠不會發生。 如果test
通過execute
確實在第一次循環后開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.