label/goto
var i = 1;
label:
console.log(i)
i++;
if (i <=100){
goto label
};
do/while
var i = 1;
do {
console.log (i)
i++
} while(i <= 100)
do {
console.log (i)
i++
if (i >100){
break
}
} while (true)
break vs. continue情況比較
var i = 1;
do {
console.log (i)
i++
if (i <= 1000) {
break // 跳出整個迴圈
}
console.log('i++', i)
} while (i<=100)
console.log('i=', i) // 直接到這
var i = 1;
do {
console.log (i)
i++
if (i <=1000) {
continue // 跑到下一圈
}
console.log('i++', i) // 會忽略掉這行
}while (i<=100)
console.log('i=', i)
while
var i = 1;
while (i <= 100){
console.log(i++) // 會先log(i)再執行++
};
console.log('i=', i);
for
for (var i = 1; i<=100; i+=2){
console.log (i)
};
break vs. continue情況比較
for (var i = 1; i<=5; i++){
if (i === 3) break // 3就跳掉了只會log出1.2
console.log (i)
};
for (var i = 1; i<=5; i++){
if (i ===3) continue // i=3時不會執行log但仍會執行++
console.log (i)
};
奇數偶數倍數
取餘數
for (var i = 1; i<=10; i++) {
if (i % 2) continue // 只印出偶數,奇數跳掉
console.log (i)
}
2倍
for (var i = 1; i<=10; i*=2){
console.log (i) // 1.2.4.8
}
結合陣列
var scores = [10, 24, 34, 42, 51]
var sum = 0
for (var i=0; i<scores.length; i++) {
sum += scores[i]
}
console.log(sum)