i++
for 迴圈內有一個所產生的值,會用 i++ 登打,
1 2 3
| for (var = 0; i < array.length; i++) { ... }
|
寫法有三種,但都是在做同一件事情
1 2 3 4 5 6 7 8 9 10
| var i = 0; console.log(i);
i = i + 1; console.log(i);
i + 1 = 2;
i++ = 1;
|
用 for 迴圈做加總
從陣列中取出資料,並使用 for 迴圈做加總的練習。
今天老闆需要知道不同分店可樂的總銷售狀況,可以這樣寫。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var shops = [ { captain: "Tim", chicken: 150, coke: 200, fries: 70, set: 99, }, { captain: "Min", chicken: 99, coke: 77, fries: 55, set: 101, }, { captain: "Mike", chicken: 105, coke: 111, fries: 75, set: 130, }, ]; //陣列資料
|
計算可樂的數量。
1 2 3 4 5 6 7 8 9
| var shopsTotal = shops.length; console.log(shopsTotal); var cokeTotal = 0; for (var i = 0; i < shopsTotal; i++) { cokeTotal += shops[i].coke; }
console.log("今年的可樂銷售額為: " + cokeTotal);
|
codepen https://codepen.io/hnzxewqw/pen/vYEOJMB
for 迴圈與 break
break 在 for 迴圈中的基本寫法:
1 2 3 4
| for (var i = 0; i < shopsTotal; i++) { console.log(i); break; }
|
沿用上方資料,會用到 break 的情況:
要找可以買 100 份炸雞的老闆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var shops = [ { captain: "Tim", chicken: 150, coke: 200, fries: 70, set: 99, }, { captain: "Min", chicken: 99, coke: 77, fries: 55, set: 101, }, { captain: "Mike", chicken: 105, coke: 111, fries: 75, set: 130, }, ]; //陣列資料
|
因為有條件出現,可以在 for 迴圈中用 if 來寫:
1 2 3 4 5 6 7 8 9 10
| var shopsTotal = shops.length; console.log(shopsTotal); for (var i = 0; i < shopsTotal; i++) { if (shops[i].chicken > 100) { console.log(shops[i].captain + "的店家有足夠 100 份炸雞"); } }
|
畫面會顯示如下:
可是只要找到一間店有賣超過 100 份炸雞就可以,所以可以加上 break, break 都是搭配 for 迴圈使用的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| var shops = [ { captain: "Tim", chicken: 150, coke: 200, fries: 70, set: 99, }, { captain: "Min", chicken: 99, coke: 77, fries: 55, set: 101, }, { captain: "Mike", chicken: 105, coke: 111, fries: 75, set: 130, }, ]; //陣列資料
var shopsTotal = shops.length; console.log(shopsTotal); for (var i = 0; i < shopsTotal; i++) { if (shops[i].chicken > 100) { console.log(shops[i].captain + "的店家有足夠 100 份炸雞"); shops[i].chicken -= 100; console.log( shops[i].captain + "的店家還剩下 " + shops[i].chicken + " 份炸雞" ); break; } }
|
呈現結果如下:
codepen https://codepen.io/hnzxewqw/pen/WNbvMOX