Định nghĩa
continue bỏ qua phần còn lại của body vòng lặp hiện tại, nhảy đến kiểm tra điều kiện của lần lặp tiếp theo.
Ví dụ while
<script>
var x = 1;
document.write("Vao vong lap<br>");
while (x < 10) {
x = x + 1;
if (x == 5) {
continue; // bo qua in khi x=5
}
document.write(x + "<br>"); // in 2,3,4,6,7,8,9,10
}
document.write("Thoat vong lap!<br>");
</script>
Ví dụ for
for (var i = 0; i < 5; i++) {
if (i === 2) continue;
console.log(i); // 0, 1, 3, 4
}
continue với Label (nested loop)
outer: for (var i = 0; i < 3; i++) {
for (var j = 0; j < 5; j++) {
if (j === 3) continue outer; // bỏ qua j=3,4, sang i tiếp
console.log(i, j);
}
}
// Output: (0,0)(0,1)(0,2) (1,0)(1,1)(1,2) (2,0)(2,1)(2,2)
Lưu ý
- Không dùng trong
switch(chỉbreak). - Trong
for,continuevẫn chạy phần iteration (i++). - Trong
while/do-while, cần tự cập nhật biến trướccontinuetránh vô tận.