js for循环

for循环基本结构

begin:进入循环时执行一次
condition:在每次循环迭代之前检查,如果为 false,停止循环
body(循环体):条件为真时,重复运行。
step:在每次循环体迭代后执行。
所以循环的流程:begin => condition=> body =>step => condition=> body =>step

for (begin; condition; step) {
  // ……循环体……
}

支持异步

async function func() {
        let arr = [2, 1, 4];
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i];
          const res = await handle(item);
          console.log(res);
        }
        console.log("end");
      }
      function handle(item) {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve(item);
          }, 1000 * item);
        });
      }
      func();//2 1 4 end

continue

for (let i = 0; i < 10; i++) {
  //如果为真,跳过循环体的剩余部分。
  if (i % 2 == 0) continue;
  alert(i); // 1,然后 3,5,7,9
}

使用 continue 跳出里层循环,继续外层循环

 outer: for (let i = 0; i < 4; i++) {
        if (i % 2 == 1) {
          for (let j = 0; j < 3; j++) {
            if (j == 1) {
              continue outer;//跳出里层循环 继续外层循环
            }
            console.log(j, "j");
          }
        }
        console.log(i, "i");
      }

输出结果

跳出循环

跳出一层循环直接使用break;跳出多层循环break

 outer: for (let i = 0; i < 4; i++) {
        console.log(i, "i");
        for (let j = 0; j < 3; j++) {
          if (j == 1) {
            break outer;
          }
          console.log(j, "j");
        }
      }
// 输出i=0; j=0

return

首先return仅在函数内部有意义
如果需要在for里面使用就需要把循环定义在函数里面,否知就会报 Illegal return statement

function func() {
        console.log("循环前");
        for (let i = 0; i < 4; i++) {
          return;
        }
        console.log("循环后");
      }
func() //循环前
原文地址:https://www.cnblogs.com/heihei-haha/p/14790509.html