javaScript 不同類型的循環

  • for循環:循環代碼塊一定的次數;和java中的循環方式一樣,只是輸出語句而已

  • For 循環

    for 循環是您在希望創建循環時常會用到的工具。

    下面是 for 循環的語法:

    for (語句 1; 語句 2; 語句 3)
      {
      被執行的代碼塊
      }
    
<!DOCTYPE html>
<html>
<body>

<script>
//
letters=["a","b","c","d","e"];
for (var i=0;i<letters.length;i++)
{

document.write(letters[i] + "<br>");

}

</script>

</body>
</html>

 

  • for/in 循環:循環遍歷對象的屬性,(NoiseDust項目中用到)

    <!DOCTYPE html>
    <html>
    <body>
    <h3>for/in循環</h3>
    
    <button onclick="firstFunction()">For/in:循環遍歷對象的("dog")屬性</button>
    <p id = "tex1"></p>
    <script>
    
    function firstFunction(){
    var a;
    var variable = "";
    var dog = {fname:"雪白",age:5,phone:17709320827,adress:"西安市雁塔區510所"};
    for(a in dog){
        variable = variable + dog[a] + "<br>";
    }
    document.getElementById("tex1").innerHTML = variable;
    }
    </script>
    </body>
    </html>

  • while循環:當指定的條件爲true執行指定的代碼塊

  • 語法

    while (條件)
      {
      需要執行的代碼
      }
    
<!DOCTYPE html>
<html>
<body>

<h3>測試循環</h3>
<button onclick="cgFunction()">點擊開始循環</button>
<p id="demo2"></p>
<script>

function cgFunction(){
  var x = "";
  var i = 0;
  while(i<5){
  x = x + "第" + i + "次循環" + "<br>";
  i++;
}
  document.getElementById("demo2").innerHTML = x;
}
</script>

</body>
</html>

  • do/while循環:是while循環的變體 ;先執行一次代碼塊,在判斷條件是否爲真之前,如果條件爲真,則繼續執行一次代碼塊

  • 語法:
do
  {
  需要執行的代碼
  }
while (條件);
<!DOCTYPE html>
<html>
<body>

<p>點擊下面的按鈕,只要 i 小於 5 就一直循環代碼塊。</p>
<button onclick="myFunction()">點擊這裏</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i=0;
do
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
while (i<5)  
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章