The methods of class Iterator
let us process data incrementally. Let’s explore where we can use them.
Iterator.from(iterable)
always returns instances ofIterator
(converting non-instances to instances as needed).iterable[Symbol.iterator]()
returns an iterator:- With all built-in data structures, the result is an instance of
Iterator
. - With other, older iterable objects, the result may not be an instance of
Iterator
.
- With all built-in data structures, the result is an instance of
Arrays, Typed Arrays, Sets and Maps have additional methods that return iterators:
- Arrays (similarly: Typed Arrays):
Array.prototype.keys()
returns an iterator over numbers.Array.prototype.values()
returns an iterator.Array.prototype.entries()
returns an iterator over key-value pairs. The keys are numbers.
- Sets:
Set.prototype.values()
returns an iterator.Set.prototype.keys()
returns an iterator. Equivalent to.values()
.Set.prototype.entries()
returns an iterator over value-value pairs (i.e., both components of the pair are the same value).
- Maps:
Map.prototype.keys()
returns an iterator.Map.prototype.values()
returns an iterator.Map.prototype.entries()
returns an iterator over key-value pairs.
The following methods return iterators:
String.prototype.matchAll()
returns an iterator over match objects.
Generators also return iterators:
function* gen() {}
assert.equal(
gen() instanceof Iterator,
true
);