<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i;
for (i=0;i<5;i++)
{
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
--循环输出标题
<p>Click the button to loop from 1 to 6, to make HTML headings.</p>
<button onclick="myFunction()">Try it</button>
<div id="demo"></div>
<script>
function myFunction()
{
var x="",i;
for (i=1; i<=6; i++)
{
x=x + "<h" + i + ">Heading " + i + "</h" + i + ">";
}
document.getElementById("demo").innerHTML=x;
}
</script>
// while 循环
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
while (i<5){
x=x + "该数字为 " + i + "<br>";
i++;
}
document.getElementById("demo").innerHTML=x;
}
</script>
// do while
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
do{
x=x + "该数字为 " + i + "<br>";
i++;
}
while (i<5)
document.getElementById("demo").innerHTML=x;
}
</script>
//break中断循环
<p>点击按钮,测试带有 break 语句的循环。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
for (i=0;i<10;i++){
if (i==3){
break;
}
x=x + "该数字为 " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
//continue跳过本次循环,继续下个循环
<p>点击下面的按钮来执行循环,该循环会跳过 i=3 的步进。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
for (i=0;i<10;i++){
if (i==3){
continue;
}
x=x + "该数字为 " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
//用for...in遍历数组内元素
<p>点击下面的按钮,循环遍历对象 "person" 的属性。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var txt="";
var person={fname:"Bill",lname:"Gates",age:56};
for (x in person){
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script>