Break 语句
break 语句可用于跳出循环。
break 语句跳出循环后,会继续执行该循环之后的代码(如果有的话):
例子:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<button type="button" οnclick="myfunction()">点击</button>
<p id="demo"></p>
<script>
function myfunction(){
var x="",i=0;
for(i=0;i<10;i++){
if(i==4){
break;
}
x=x + "The number is " + i + "<br>"
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
效果图:
Continue 语句
continue 语句中断循环中的迭代,如果出现了指定的条件,然后继续循环中的下一个迭代。
例子:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<button type="button" οnclick="myfunction()">点击</button>
<p id="demo"></p>
<script>
function myfunction(){
var x="",i=0;
for(i=0;i<10;i++){
if(i==4){
continue;
}
x=x + "The number is " + i + "<br>"
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
效果图:
JavaScript 标签
正如您在 switch 语句那一章中看到的,可以对 JavaScript 语句进行标记。
如需标记 JavaScript 语句,请在语句之前加上冒号:
label: 语句
break 和 continue 语句仅仅是能够跳出代码块的语句。
语法
break labelname; continue labelname;
continue 语句(带有或不带标签引用)只能用在循环中。
break 语句(不带标签引用),只能用在循环或 switch 中。
通过标签引用,break 语句可用于跳出任何 JavaScript 代码块:
实例
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<script>
letter = ["abc","def","ghi","jkl"];
list:{
document.write(letter[0] + "<br>");
document.write(letter[1] + "<br>");
document.write(letter[2] + "<br>");
break list;
document.write(letter[3] + "<br>");
document.write(letter[4] + "<br>");
document.write(letter[5] + "<br>");
}
</script>
</body>
</html>