Break và Continue trong Dart
1. Giới thiệu
break- Thoát khỏi vòng lặp ngay lập tứccontinue- Bỏ qua lần lặp hiện tại, chuyển sang lần tiếp theo
2. Lệnh break
void main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Thoát khi i = 5
}
print(i);
}
// Output: 1, 2, 3, 4
}3. Lệnh continue
void main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Bỏ qua khi i = 3
}
print(i);
}
// Output: 1, 2, 4, 5
}4. Break trong while
void main() {
int count = 0;
while (true) {
count++;
print(count);
if (count >= 5) {
break; // Thoát vòng lặp vô hạn
}
}
}5. Continue trong while
void main() {
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue; // Bỏ qua số chẵn
}
print(i);
}
// Output: 1, 3, 5, 7, 9
}6. Vòng lặp lồng nhau với label
void main() {
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outerLoop; // Thoát cả 2 vòng lặp
}
print('$i - $j');
}
}
}7. Continue với label
void main() {
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue outerLoop; // Tiếp tục vòng ngoài
}
print('$i - $j');
}
}
}8. Ví dụ thực tế
// Tìm phần tử trong list
void main() {
var items = ['a', 'b', 'c', 'd'];
for (var item in items) {
if (item == 'c') {
print('Tìm thấy: $item');
break;
}
}
}// Bỏ qua giá trị null
void main() {
var items = [1, null, 2, null, 3];
for (var item in items) {
if (item == null) continue;
print(item);
}
// Output: 1, 2, 3
}📝 Tóm tắt
break- Thoát vòng lặp hoàn toàncontinue- Bỏ qua lần lặp hiện tại- Dùng label cho vòng lặp lồng nhau
- Giúp kiểm soát luồng thực thi
Last updated on