Exit the loop break
The format is as follows:
for(初始条件;判断条件;循环后条件值更新)
{ if(特殊情况)
{break;}
循环代码
}When a special situation is encountered, the loop will end immediately. Take a look at the example below, which outputs 10 numbers. If the value is 5, it stops outputting.
<html>
<head>
<script>
var num;
for(num=1;num<10;num++){
if (num==5)
{
break;//如果num是5,退出循环。
}
document.write("数值"+num+"<br />");
}
</script>
</head>
<body>
</body>
</html>The output results are as follows

Note: When num=5, the loop will end and the content of the subsequent loop will not be output.
<!DOCTYPE html>
<html>
<body>
<p>点击按钮,测试带有 break 语句的循环。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="",i=0;
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>