Loop 可以在變數符合條件時,重複執行一段 code,
一直到不符合條件時才會停止。
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
document.getElementById("demo").innerHTML = text;
可以寫成
var cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
var text = "";
var i;
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
寫出來的結果是這樣BMW
Volvo
Saab
Ford
Fiat
Audi
i = 0
:代表了變數的初始值。i < cars.length
:指出了變數的限制,這邊限制變數必須小於cars 這個array的length。i++
:代表了增量,有點像數學中等差數列的公差,這裡代表的是 i + 1,如果把這邊改成 i += 2
,最後寫出來的結果就會是:BMW
Saab
Fiat
寫完如果不對造成無線迴圈...
就會當機...