dart list 迭代
Before doing some dedicated study and practice, iterables were kind of confusing to me. If you’re like I was, then this article is for you. It turns out they’re not that difficult. I’ll explain what iterables are and how they differ from iterators. I’ll also show you a real example of how to make your own iterable.
在进行一些专门的学习和练习之前,可迭代对象使我有些困惑。 如果您像我一样,那么本文适合您。 事实证明,它们并不难。 我将解释什么是可迭代的,以及它们与迭代器的区别。 我还将向您展示如何使自己的迭代成为现实的示例。
什么是可迭代的? (What is an iterable?)
An iterable is one kind of collection in Dart. It’s a collection that you can move through sequentially one element at a time. List
and Set
are two common examples of iterable collections. Queue
is another one, though less common.
可迭代是Dart中的一种集合。 这是一个集合,您可以一次依次浏览一个元素。 List
和Set
是可迭代集合的两个常见示例。 Queue
是另一个Queue
,尽管不太常见。
If you look at the source code of List
, you’ll see the following:
如果您查看List
的源代码,则会看到以下内容:
abstract class List<E> implements EfficientLengthIterable<E> { ... }
EfficientLengthIterable
is itself a subclass of Iterable
, a class you’ll learn more about later. So by its very definition, you can see that lists are iterables.
EfficientLengthIterable
本身是Iterable
的子类,您将在稍后了解更多信息。 因此,按照其定义,您可以看到列表是可迭代的。
Next you’ll see some of the benefits of being an iterable collection.
接下来,您将看到成为可迭代集合的一些好处。
遍历集合的元素 (Iterating over the elements of a collection)
Being able to move sequentially through all the elements of a collection is a prerequisite for using a for-in
loop.
能够顺序移动集合的所有元素是使用for-in
循环的先决条件。
final myList = [2, 4, 6];
for (var number in myList) {
print(number);
}
Since List
is iterable, you’re able to iterate over it.
由于List
是可迭代的,因此您可以对其进行迭代。
Not all Dart collections are iterables, though. Most notably, Map
isn’t. That’s why you can’t directly use a for-in
loop with the elements of Map
collection.
不过,并非所有Dart集合都是可迭代的。 最值得注意的是, Map
不是。 这就是为什么您不能直接对Map
集合的元素使用for-in
循环。
If you try to do the following:
如果您尝试执行以下操作:
final myMap = {'a': 1, 'b':2, 'c':3};
for (var element in myMap) {
print(element);
}
You’ll get an error:
您会得到一个错误:
The type 'Map<String, int>' used in the 'for' loop must implement Iterable.
However, maps do have keys
and values
properties, which are of type Iterable
. That means you can iterate over either of them. Here’s an example of iterating over the keys
:
然而,地图确实有keys
和values
属性,这是类型的Iterable
。 这意味着您可以遍历任何一个。 这是一个遍历keys
的示例:
final myMap = {'a': 1, 'b':2, 'c':3};
for (var key in myMap.keys) {
print('key: $key, value: ${myMap[key]}');
}
可迭代的其他好处 (Other benefits of iterables)
An iterable gives you access to lots of other features besides being able to use them with a for-in
loop. For example, there are quite a few higher order methods available, such as map