JavaScript循环
在JS中循环方式有三种
- while循环(当指定的条件为 true 时循环指定的代码块)
while (条件)
{
需要执行的代码块
比如:alert("当满足while的条件为true就可以看见我了!")
}
while循环例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</h1>
<button onclick="firstFunction()"> 点我会弹出弹窗</button>
<script>
function firstFunction(){
a="",i=0;
while(i<5){
a="该数字为"+i
alert(a)
i++;
}
}
</script>
</body>
</html>
- do-while循环(当指定的条件为 true 时循环指定的代码块)
do
{
需要执行的代码块
比如:alert("当满足while的条件为true就可以看见我了!")
}
while (条件);
do-while循环例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</h1>
<button onclick="firstFunction()"> 点我会弹出弹窗</button>
<script>
function firstFunction(){
a="",i=0;
do{
a="该数字为"+i
alert(a)
i++;
}
while(i<5)
}
</script>
</body>
</html>
- for循环( 循环代码块一定的次数)
for循环:语句1首先被执行,语句2运行循环(代码块)的条件,语句3在循环代码块被执行后才会被执行
for (语句 1; 语句 2; 语句 3)
{
被执行的代码块
比如:alert("当满足for的条件就可以看见我了!")
}
for循环例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</h1>
<button onclick="firstFunction()"> 点我会弹出弹窗</button>
<script>
function firstFunction(){
a=""
for(var i =0;i<5;i++){
a="该数字为"+i
alert(a)
}
}
</script>
</body>
</html>
在循环中break 语句用于跳出循环。continue 用于跳过循环中的一个迭代。
break 语句跳出循环后,会继续执行该循环之后的代码(如果有的话)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</h1>
<button onclick="firstFunction()"> 点我会弹出弹窗</button>
<script>
function firstFunction(){
a=""
for(var i =0;i<5;i++){
if(i==2)break
a="该数字为"+i
alert(a)
}
}
</script>
</body>
</html>
在下面的循环中continue 语句中断当前的循环中的迭代,然后继续循环下一个迭代。 以下例子在值为2 时,直接跳过:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</h1>
<button onclick="firstFunction()"> 点我会弹出弹窗</button>
<script>
function firstFunction(){
a=""
for(var i =0;i<5;i++){
if(i==2)break
a="该数字为"+i
alert(a)
}
}
</script>
</body>
</html>