详解JavaScript中循环控制语句的用法
详解JavaScript中循环控制语句的用法
发布时间:2016-12-30 来源:查字典编辑
摘要:JavaScript提供完全控制来处理循环和switch语句。可能有一种情况,当你需要退出一个循环,但未达到其底部。也可能有一种情况,当要跳...

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!

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类