var i=0; var sum=0; while (i < 10) { sum += i; i++; } alert(sum); //55
var i=0; var sum=0; do { sum += i; i++; } while (i < 10)
Use
var i=0; var sum=0; while (i < 10) { sum += i; if (i == 4) break; i++; } alert(i); //4 alert(sum); //0+1+2+3+4=10
Use
var i=0; var sum=0; while (i < 10) { i++; if (i == 4) continue; else sum += i; } alert(i); //10 alert(sum); //51
We must put i++ before the if statement, otherwise, if the i
is not increased, the while loop will keep running forever till
the browser collapse.