標籤:onclick log asc oop bsp title 工具 html for 迴圈
JavaScript 支援不同類型的迴圈:
- for - 迴圈代碼塊一定的次數
- for/in - 迴圈遍曆對象的屬性
- while - 當指定的條件為 true 時迴圈指定的代碼塊
- do/while - 同樣當指定的條件為 true 時迴圈指定的代碼塊
For 迴圈
for 迴圈是您在希望建立迴圈時常會用到的工具。
文法:
for (語句 1; 語句 2; 語句 3){ 被執行的代碼塊}
while 迴圈
while 迴圈會在指定條件為真時迴圈執行代碼塊。
文法:
while (條件){ 需要執行的代碼}do/while 迴圈
do/while 迴圈是 while 迴圈的變體。該迴圈會在檢查條件是否為真之前執行一次代碼塊,然後如果條件為真的話,就會重複這個迴圈。
文法:
do{ 需要執行的代碼}while (條件);
demo:
<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>迴圈語句</title> </head> <body> <script type="text/javascript" src="test.js" ></script> <button onclick="loop()">迴圈語句</button> </body></html>
js裡面的迴圈語句邏輯代碼:
/** * 迴圈語句 */function loop(){ document.write("----------for迴圈遍曆-----------" + "<br>"); cars = ["BMW", "Volvo", "Saab", "Ford"]; for (var i = 0; i < cars.length; i++) { document.write(cars[i] + "<br>"); } document.write("---------------------" + "<br>"); var i = 0, len = cars.length; for (; i < len;) { document.write(cars[i] + "<br>"); i++; } document.write("----------for/in 語句迴圈遍曆對象的屬性-----------" + "<br>"); var x; var txt = ""; var person = { fname: "Bill", lname: "Gates", age: 56 }; //通過for in 進行對象遍曆 for (x in person) { //字串拼接,通過+ txt = txt + person[x]; } document.write(txt + "<br>"); document.write("----------while迴圈語句----------" + "<br>"); var x = "", i = 0; while (i < 5) { x = x + "該數字為 " + i + "<br>"; i++; } document.write(x + "<br>"); document.write("----------do while迴圈語句----------" + "<br>"); var x = "", i = 0; do { x = x + "the number is " + i + "<br>"; i++; } while (i < 5) document.write(x + "<br>");}
JavaScript -- 迴圈語句