2014-01-06 93 views
0

好的,我正在處理循環分配問題。 我應該爲前4個循環使用「while」循環,剩下的15個循環使用「for」循環。問題是while循環中的第一個4按順序正確地按照它們應該按順序正確地打印到控制檯。Javascript以循環間隔循環播放

其餘15只打印到控制檯奇數間隔IE:「5,7,9,11 ......」

這有什麼錯我的for循環?

var currentGen = 1; 
var totalGen = 19; 
var totalMW = 0; 

while(currentGen <= 4){ 
    console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " +   (totalMW = totalMW + 62) + " MW!"); 
    currentGen++; 
    } 

for(currentGen = 5; currentGen < 20; currentGen = currentGen + 1){ 
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + (totalMW = totalMW + 124) + " MW!"); 
    currentGen++; 
    } 

回答

0

因爲,for循環有它自己的增量部分。你不必在循環體內再次做到這一點

for(currentGen = 5; currentGen < 20; currentGen = currentGen + 1) { //incrementing 
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + (totalMW = totalMW + 124) + " MW!"); 
    // currentGen++; // Incrementing again 
    } 
4

,你既有

currentGen = currentGen + 1 

currentGen++; 

所以每次你增加2次迭代,而不是1只是做了一個或另一個。

0

這是因爲你不應該在for循環內有currentGen ++行。 for循環執行該可變增量部分。