JavaScript 中 break 语句和 continue 语句的区别是什么?
break 语句
break 语句用于提前退出循环,跳出包含它的花括号。break 语句会退出循环。
让我们来看一个 JavaScript 中 break 语句的例子。下面的例子演示了 break 语句与 while 循环的用法。注意,一旦 x 达到 5,循环就会提前退出,并执行紧跟在闭合花括号后面的 document.write(..) 语句。
示例
<html>
<body>
<script>
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>
</body>
</html>continue 语句
continue 语句告诉解释器立即开始循环的下一个迭代,并跳过剩余的代码块。当遇到 continue 语句时,程序流程会立即移动到循环检查表达式,如果条件仍然为真,则开始下一个迭代;否则,控制权将退出循环。
continue 语句会跳过循环中的一个迭代。此示例演示了 continue 语句与 while 循环的用法。注意如何使用 continue 语句来跳过变量 x 中的索引达到 8 时的打印操作。
示例
<html>
<body>
<script>
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10) {
x = x+ 1;
if (x == 8){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
</script>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP