不同类型的循环
JavaScript 支持不同类型的循环:
- for - 循环代码块一定的次数
- for/in - 循环遍历对象的属性
- while - 当指定的条件为 true 时循环指定的代码块
- do/while - 同样当指定的条件为 true 时循环指定的代码块
1、for循环
<DOCTYPE html> <html> <head> <mata charset="utf-8"> <title>for循环</title> </head> <body> <p>点击按钮循环代码5次</p> <button onclick="myFnction()">点击这里</button> <p id="demo"></p> <script> function myFunction() { var x=" "; for(var i=0;i<5;i++) { x=x+"该数字为"+i+"<br>" } document.getElemmentById("demo").innerHTML=x; } </script> </body> </html>
2、while循环
语法:
while (条件) do
{ {需要执行的代码 或
} }while(条件)