发布于 2015-07-31 15:05:51 | 310 次阅读 | 评论: 0 | 来源: 网络整理

JavaScript提供完全控制来处理循环和switch语句。可能有一种情况,当你需要退出一个循环,但未达到其底部。也可能有一种情况,当要跳过的码块的一部分,并直接开始下一个迭代。

为了处理这些情况下,JavaScript提供了break和continue语句。这些语句是用来马上退出任何循环或启动循环的下一次迭代。

break 语句:

break语句,这是简单地用switch语句介绍,用于提前退出循环,打破封闭的花括号。

例子:

这个例子说明了如何使用break语句同while循环。请注意循环打破了初期由x到5,document.write(..) 语句的正下方,以右大括号:


<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
  if (x == 5){ 
     break;  // breaks out of loop completely
  }
  x = x + 1;
  document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

这将产生以下结果:


Entering the loop
2
3
4
5
Exiting the loop!

我们已经看到break语句在switch语句中使用。

continue 语句:

continue语句告诉解释器立即启动循环的下一次迭代,并跳过其余的代码块。

当遇到continue语句,程序流程将立即转移到循环检查表达式,如果条件保持真,那么就开始下一个迭代,否则控制退出循环。

例子:

这个例子说明使用continue语句同while循环。请注意continue语句用于跳过打印时指数变量x到达5:


<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
  x = x + 1;
  if (x == 5){ 
     continue;  // skill rest of the loop body
  }
  document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

这将产生以下结果:


Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!

使用标签来控制流程:

从JavaScript1.2开始,标签可以与break及continue使用,继续更精确地控制流程。

标签是简单的标识符随后被施加到一个语句或代码块冒号。看到两个不同的例子来了解标签使用突破,并继续。

注:换行符是不是继续还是分手声明,其标签名称之间允许的。此外,不应该有一个标签名称和相关联的回路之间的任何其它声明。

实例1:


<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop:   // This is the label name
for (var i = 0; i < 5; i++)
{
  document.write("Outerloop: " + i + "<br />");
  innerloop:
  for (var j = 0; j < 5; j++)
  {
     if (j >  3 ) break ;         // Quit the innermost loop
     if (i == 2) break innerloop; // Do the same thing
     if (i == 4) break outerloop; // Quit the outer loop
     document.write("Innerloop: " + j + "  <br />");
   }
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

这将产生以下结果:


Entering the loop!
Outerloop: 0
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 1
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 2
Outerloop: 3
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 4
Exiting the loop!

实例2:


<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop:   // This is the label name
for (var i = 0; i < 3; i++)
{
   document.write("Outerloop: " + i + "<br />");
   for (var j = 0; j < 5; j++)
   {
      if (j == 3){
         continue outerloop;
      }
      document.write("Innerloop: " + j + "<br />");
   } 
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

这将产生以下结果:


Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务