日期:2014-05-16  浏览次数:20374 次

新手学JS,请教一个循环的问题。

<!DOCTYPE html>
<html>
<body>

<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 + "The number is " + i + "<br>";
  }
document.getElementById("demo").innerHTML=x;
}
</script>


这样将输出

The number is 0
The number is 1
The number is 2

问题是 如果想输出0-9,唯独不输出3,应该怎么做呢?

------解决方案--------------------
continue
break: 终止整个循环, continue : 终止本次循环,继续下次循环

<!DOCTYPE html>
<html>
<body>

<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) {
                continue;
            }
            x = x + "The number is " + i + "<br>";
        }
        document.getElementById("demo").innerHTML = x;
    }
</script>