JavaScript-5循環
For循環:
例一:
<html>
<body>
<script type="text/javascript">
for (i = 0; i <= 5; i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
實圖:
例二:
<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">標題 " + i+"</h" + i + ">")
}
</script>
</body>
</html>
實圖:
While循環:
例一:
<html>
<body>
<script type="text/javascript">
i = 0
while (i <= 5)
{
document.write("The number is " + i)
document.write("<br>")
i++
}
</script>
</body>
</html>
實圖:同for例一。
Do while 循環:(先執行,在判斷)
<html>
<body>
<script type="text/javascript">
var i=0
do
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
while (i<0)
</script>
</body>
</html>
實圖:
Break 語句:break終止循環的運行,然後執行循環之後的代碼
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){break}
document.write(i+" ")
}
</script>
</body>
</html>
結果爲:0 1 2 。
Continue語句:終止當前循環,然後從下一個值繼續運行。
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){continue}
document.write(i+" ")
}
</script>
</body>
</html>
結果爲:0 1 2 4 5 6 7 8 9 10