title: continue

continue

原文地址

在本教程中,你将学习 TypeScript 中的 continue 语句。

continue 语句用于辅助控制循环,比如 for 循环,while 循环,或者 do while 循环。continue 语句会跳到当前循环的末尾,然后开始下一个循环迭代。

在 for 循环中使用 continue 语句

下面的例子演示了如何在 for 循环中使用 continue 语句:

  1. for (let index = 0; index < 9; index++) {
  2. // if index is odd, skip it
  3. if (index % 2) continue;
  4. // the following code will be skipped for odd numbers
  5. console.log(index);
  6. }

输出:

  1. 0
  2. 2
  3. 4
  4. 6
  5. 8

在这个例子中:

  • 首先,循环 09 这几个数字;
  • 然后,当数字是奇数的时候,使用 continue 语句跳过把数字输出到控制台的操作,而当数字是偶数的时候,把它输出到控制台中。

在 while 循环中使用 continue 语句

下面的例子展示如何在 while 循环中使用 continue 语句,它和上面的例子的返回结果是一样:

  1. let index = -1;
  2. while (index < 9) {
  3. index = index + 1;
  4. if (index % 2) continue;
  5. console.log(index);
  6. }

输出:

  1. 0
  2. 2
  3. 4
  4. 6
  5. 8

在 do while 循环中使用 continue 语句

下面的例子展示如何在 do while 循环中使用 continue 语句,它返回 999 之间存在的偶数的数量:

  1. let index = 9;
  2. let count = 0;
  3. do {
  4. index += 1;
  5. if (index % 2) continue;
  6. count += 1;
  7. } while (index < 99);
  8. console.log(count); // 45