for 循環是您在希望創建循環時常會用到的工具。
下面是 for 循環的語法:
for (語句 1; 語句 2; 語句 3)
{
被執行的代碼塊
}
語句 1 在循環(代碼塊)開始前執行
語句 2 定義運行循環(代碼塊)的條件
語句 3 在循環(代碼塊)已被執行之後執行
案例:
<script>
for(i=0;i<=5;i++){
document.write("the number is "+ i + "</br>");
}
</script>
如上所示,語句一在代碼塊開始前執行,將0賦值給i;語句2定義運行循環的條件,i<=5;語句3再循環已被執行後操作i++;
效果如下:
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
the number is 5