這篇文章給大家分享的是有關JavaScript中循環的實現方法的內容。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。
for 循環
在腳本的運行次數已確定的情況下使用 for 循環。
語法:
for (變量=開始值;變量<=結束值;變量=變量+步進值)
{
需執行的代碼
}解釋:下面的例子定義了一個循環程序,這個程序中 i 的起始值為 0。每執行一次循環,i 的值就會累加一次 1,循環會一直運行下去,直到 i 等于 10 為止。
注釋:步進值可以為負。如果步進值為負,需要調整 for 聲明中的比較運算符。
<html>
<body>
<script>
var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10
while 循環用于在指定條件為 true 時循環執行代碼。
while
(變量<=結束值)
{
需執行的代碼
}注意:除了<=,還可以使用其他的比較運算符。
解釋:下面的例子定義了一個循環程序,這個循環程序的參數 i 的起始值為 0。該程序會反復運行,直到 i 大于 10 為止。每次運行i的值會增加 1。
<html>
<body>
<script>
var i=0
while (i<=10)
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
</script>
</body>
</html>The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10
do...while 循環是 while 循環的變種。該循環程序在初次運行時會首先執行一遍其中的代碼,然后當指定的條件為 true 時,它會繼續這個循環。所以可以這么說,do...while 循環為執行至少一遍其中的代碼,即使條件為 false,因為其中的代碼執行后才會進行條件驗證。
do
{
需執行的代碼
}
while
(變量<=結束值)<html>
<body>
<script>
var i=0
do
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
while (i<0)
</script>
</body>
</html>The number is 0
感謝各位的閱讀!關于JavaScript中循環的實現方法就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。