JavaScript 循环的Break 和 Continue

JavaScript 的 break 和 continue 语句

有两种特殊的语句可以在循环中使用: break 和 continue。

—————————————————————————–
Break

break 命令用来打断整个循环, 并继续执行循环后面的代码(如果有的话)。

例子

<html>
<body>
<script type=”text/javascript”>
var i=0
for (i=0;i<=10;i++)
{
if (i==3){break}
document.write(“The number is ” + i)
document.write(“<br />”)
}
</script>
</body>
</html>

结果

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

———————————————————————
Continue

continue命令将打断当前这次循环,而继续执行下一个循环值。

Example

<html>
<body>
<script type=”text/javascript”>
var i=0
for (i=0;i<=10;i++)
{
if (i==3){continue}
document.write(“The number is ” + i)
document.write(“<br />”)
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
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

5 Comments

  1. BAI:

    和C很像!

  2. rubbish:

    趋近于相等

  3. 新手:

    var i=-5
    do
    {
    document.write(“The number is” + i)
    document.write(“”)
    i=i+1
    if(i==3){continue}
    }
    while (i<10)

    可以问一个很弱智是问题么.我是个新手 上面的代码为什么他不打断3呢…如果我换成break 2以后的都不会显示了?是不是逻辑出错,,还是这样的循环不能用这样的语句!

  4. zz:

    你上面写错了一个地方,应该是i++,不是i+1

  5. anyone:

    回复新手:

    你的程序顺序搞错了。i=3的时候,你已经先写了document.write,然后跳出本次循环就没有意义了。应该如下这样:

    var i=-5
    do {
    i = i+1;
    if(i==3){continue}
    document.write(“The number is” + i);
    document.write(“”)
    }
    while (i<=10)

Leave a comment