2017-10-07 45 views
0

我試圖回答這個question我遇到了一個奇怪的循環條件。奇怪的內部循環沒有執行某些迭代

for (index1 = 1; index1 < 8; index1++) { 
    var op = '#'; 
    for (index2 = index1; index2 - 1; index2--) { //this loop is weird to me 
    op = op + '#'; 
    } 
    console.log(op); 
} 

在檢查內循環多少次迭代使得每個外循環迭代,我得到這樣的:

var x = 0; 
 

 
for (index1 = 1; index1 < 8; index1++) { 
 
    //var op = '#'; 
 
    for (index2 = index1; index2 - 1; index2--) { 
 
    var log = {}; 
 
    log.a = x; //check value before increment 
 
    x++; 
 
    log.b = x; //check value after increment 
 
    console.log(`outer: ${index1}, inner: ${index2}`, log); 
 
    } 
 
    console.log(x); 
 
    x = 0; 
 
    //console.log(op); 
 
}

正如你所看到的,它記錄0, 1, 2, 3, 4, 5, 6

我的問題是:

是第一個外循環迭代不迭代的內部循環,因爲index2 - 1等於零,這是falsy?

+0

嘗試在調試器中逐行執行代碼。 –

+2

'index2 - 1'有點尷尬。 –

+0

在內部循環中添加'console.log',並且記錄值 –

回答

1

是內循環迭代未在所述第一外部循環迭代因爲索引2 - 1等於零,這是falsy?

這是正確的。任何提供給條件的錯誤值立即停止循環。

Falsey值0NaNnullundefined""false

+0

由於您是第一個發佈答案的人,所以您的投票是這樣的,儘管@Someprogrammerdude在澄清我的猜測後也應該獲得讚譽。儘管如此,評論。 –