摘要:在本教程中,您将学习 TypeScript continue
语句。
continue
语句用于控制循环,例如 for
循环、while
循环或 do...while
循环。
continue
语句跳到循环末尾并继续下一次迭代。
在 for 循环中使用 TypeScript continue 语句
以下示例说明如何在 for
循环中使用 continue
语句
for (let index = 0; index < 9; index++) {
// if index is odd, skip it
if (index % 2)
continue;
// the following code will be skipped for odd numbers
console.log(index);
}
Code language: TypeScript (typescript)
输出
0
2
4
6
8
Code language: TypeScript (typescript)
在这个例子中
- 首先,循环遍历从 0 到 9 的数字。
- 然后,如果当前数字是奇数,则使用
continue
语句跳过将数字输出到控制台的操作。如果当前数字是偶数,则将其输出到控制台。
在 while 循环中使用 TypeScript continue 语句
以下示例演示如何在 while
循环中使用 continue
语句。它返回与上述示例相同的结果。
let index = -1;
while (index < 9) {
index = index + 1;
if (index % 2)
continue;
console.log(index);
}
Code language: TypeScript (typescript)
输出
0
2
4
6
8
Code language: TypeScript (typescript)
在 do while 循环中使用 TypeScript continue 语句
以下示例演示如何在 do...while
循环中使用 continue
语句。它返回从 9
到 99
的偶数个数
let index = 9;
let count = 0;
do {
index += 1;
if (index % 2)
continue;
count += 1;
} while (index < 99);
console.log(count); // 45
Code language: TypeScript (typescript)
总结
- 使用 TypeScript
continue
语句跳到循环末尾并继续下一次迭代。
本教程是否有帮助?