0
点赞
收藏
分享

微信扫一扫

JavaScript-while循环

if 的格式

if(条件表达式){
条件满足执行的语句;
}

if 的特点

  • 只有条件表达式为真才会执行后面 {} 中的代码。
  • 大括号中的代码只会被执行一次。

while 的格式

while(条件表达式){
条件满足执行的语句;
}

while 的特点

  • 只有条件表达式为真才会执行后面 {} 中的代码。
  • 大括号中的代码有可能会被执行多次。

while 的执行流程

  1. 首先会判断条件表达式是否为真, 如果为真就执行后面 {} 中的代码。
  2. 执行完后面 {} 中的代码, 会再次判断条件表达式是否还为真。
  3. 如果条件表达式还为真, 那么会再次执行后面 {} 中的代码。
  4. 重复 1 ~ 3, 直到条件表达式不为真为止。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
console.log("发射子弹1");
console.log("发射子弹2");
console.log("发射子弹3");
console.log("发射子弹4");
console.log("发射子弹5");
console.log("发射子弹6");
console.log("发射子弹7");
console.log("发射子弹8");
console.log("发射子弹9");
console.log("发射子弹10");
</script>
</head>
<body>

</body>
</html>

JavaScript-while循环_循环结构

书写循环结构的规则

  1. 不管三七二十一先写上循环结构的代码。
  2. 将需要重复执行的代码拷贝到 {} 中。
  3. 再 () 中指定循环的结束条件。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
let num = 1;
while (num <= 10) {
console.log("发射子弹" + num);
num++;
}
</script>
</head>
<body>

</body>
</html>

JavaScript-while循环_html_02

while 注意点

什么是死循环


条件表达式永远为真的循环结构我们称之为死循环。


什么是循环体


循环结构后面的 {} 我们称之为循环体。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
while (true) {
console.log("BNTang");
}
</script>
</head>
<body>

</body>
</html>

JavaScript-while循环_大括号_03


和 if 一样对于非 Boolean 类型的值, 会先转换为 Boolean 类型再判断。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
while (null) {
console.log("被执行了");
}
</script>
</head>
<body>

</body>
</html>

JavaScript-while循环_循环结构_04

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
while (1) {
console.log("BNTang");
}
</script>
</head>
<body>

</body>
</html>

JavaScript-while循环_大括号_03


和 if 一样 while 后如果只有一条语句它可以省略大括号。
和 if 一样如果省略了后面的 {}, 那么只有紧随其后的那条语句受到控制。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
while (false)
console.log("语句A");
console.log("语句B");
</script>
</head>
<body>

</body>
</html>

JavaScript-while循环_循环结构_06


和 if 一样, 不能在 () 后面写分号 ​​(;)​


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
while (false) ;
{
console.log("语句A");
console.log("语句B");
}
</script>
</head>
<body>

</body>
</html>

JavaScript-while循环_循环结构_07


最简单死循环写法


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script>
while (1) ;
</script>
</head>
<body>

</body>
</html>




举报

相关推荐

0 条评论