在 Dart 中,有哪些循环操作?
- while
- do-while
- for
- for-in
- for-each
- map
while
int i = 1;
while (i <= 5) {
print(i);
i++;
}
// 1
// 2
// 3
// 4
// 5
do-while
int i = 1;
do {
print(i);
i++;
} while (i <= 5);
// 1
// 2
// 3
// 4
// 5
C 语言风格的 for 循环
const numbers = [1, 2, 3, 4, 5];
for (var i = 0; i < numbers.length; i++) {
print(numbers[i]);
}
// 1
// 2
// 3
// 4
// 5
for-in 循环
const numbers = [1, 2, 3, 4, 5];
for (final number in numbers) {
print(number);
}
// 1
// 2
// 3
// 4
// 5
for-each 循环
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => print(number));
// 1
// 2
// 3
// 4
// 5
for-each 底层实现也是使用了 for-in:
abstract class Iterable<E> {
/// Invokes [action] on each element of this iterable in iteration order.
void forEach(void action(E element)) {
for (E element in this) action(element);
}
}
map 循环
const numbers = [1, 2, 3, 4, 5];
final newNumbers = numbers.map((number) => number * number);
print(newNumbers);
// (1, 4, 9, 16, 25)