JavaScript-for 循环

for 循环的格式

          1         2/5/8          4/7
for (初始化表达式; 条件表达式; 循环后增量表达式) {
          3/6
    需要重复执行的代码;
}

for 循环的特点

for 循环的特点和 while 循环的特点一样, 只有条件表达式为真, 才会执行循环体。

for 循环的执行流程

  1. 首先会执行 初始化表达式, 并且只会执行一次
  2. 判断条件表达式是否为真, 如果条件表达式为真, 就执行循环体
  3. 执行完循环体就会执行循环后的增量表达式
  4. 重复 2 ~ 3, 直到条件表达式不为真为止

while 与 for 循环的对比

while

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        // 1.初始化表达式
        let num = 1;
        
        // 2. 条件表达式
        while (num <= 10) {
            console.log("发射子弹" + num);
        
            // 3.循环后增量表达式
            num++;
        }
    </script>
</head>
<body>
</body>
</html>

for

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        // 1.初始化表达式
        // let num = 1;

        // 2. 条件表达式
        
        for (let num = 1; num <= 10; num++) {
            console.log("发射子弹" + num);

            // 3.循环后增量表达式
            // num++;
        }
    </script>
</head>
<body>
</body>
</html>

for 注意点

在 for 循环中 "初始化表达式""条件表达式""循环后增量表达式" 都可以不写,如果不写就相当于 while(1);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        // while 循环不能省略条件表达式
        while () {
            console.log("123");
        }
    </script>
</head>
<body>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo</title>
    <script type="text/javascript">
        // for 循环是可以省略条件表达式的, 默认就是真
        for (; ;) {
            console.log("123");
        }
    </script>
</head>
<body>
</body>
</html>

其它注意点和 while 循环一样。

posted @ 2021-06-29 16:01  BNTang  阅读(82)  评论(0编辑  收藏  举报