2014-01-06 168 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循环执行该可变增量部分。