Iterator
(Iterator) is a type introduced by ES6interface, used forSequential access Iterable object(Array
、Set
、Map
、String
、arguments
, custom objects, etc.).
Iterator has three functions:
- Provide a unified and simple access interface for various data structures
- Enable members of data structures to be arranged in some order
- ES6 has created a new traversal command for…of loop, and the Iterator interface is mainly for for…of consumption.
1. Basic concepts of iterators
(1) What is an iterator?
Iterator is aSpecial Objects,supplynext()
Method, each call returns:
{ value: Current value, done: Is it done }
whendone: true
when, it means the iteration ends.
Iterator traversal process
// The traversal process of Iterator is as follows:1. Create a pointer icon,Point to the starting position of the current data structure 2. The first call refers to the object next method,Pointers can be pointed to the first member of the data structure 3. The second call refers to the object next method,The pointer points to the second member of the data structure 4. Continuously call the targeted image next method,Until it points to the end of the data structure // Every time the next method is called, an object containing the properties of value and done will be returned.{ value: The value of the current member, done: Boolean value,Indicates whether the traversal has ended }
2. Generate an iterator
(1) Create iterator manually
function createIterator(arr) { let index = 0; return { next: function () { return index < ? { value: arr[index++], done: false } : { value: undefined, done: true }; } }; } let iterator = createIterator(["a", "b", "c"]); (()); // { value: 'a', done: false } (()); // { value: 'b', done: false } (()); // { value: 'c', done: false } (()); // { value: undefined, done: true }
📌 Every timenext()
Called, will returnvalue
And move forward.
(2) Use
allIterable object(Array
、Set
、Map
AllThe default iterator, can be usedaccess:
let arr = ["x", "y", "z"]; let iterator = arr[](); (()); // { value: 'x', done: false } (()); // { value: 'y', done: false } (()); // { value: 'z', done: false } (()); // { value: undefined, done: true }
📌 Arrays, strings, Sets, and Map are all, can be iterated directly.
(3) Custom object iterator
Normal objectNoThe default iterator needs to be implemented manually:
let myObj = { data: [10, 20, 30], []: function () { let index = 0; return { next: () => { return index < ? { value: [index++], done: false } : { value: undefined, done: true }; } }; } }; let iter = myObj[](); (()); // { value: 10, done: false } (()); // { value: 20, done: false } (()); // { value: 30, done: false } (()); // { value: undefined, done: true }
📌 The object does not have a default iterator, it needs to be implementedOnly use
for...of
。
3. for...of traversal iterator
All ImplementationsAll objects can be used
for...of
Traversal:
let arr = ["A", "B", "C"]; for (let char of arr) { (char); } // A // B // C
📌 CompareforEach()
,for...of
Can be used withbreak
、continue
Use together.
4. Iterable objects
✅ Can be usedfor...of
、
The object of
Array
String
Set
Map
arguments
NodeList
- Custom object (need to be implemented
)
5. Iterators for Set and Map
(1) Set
Iteration
let mySet = new Set(["apple", "banana", "cherry"]); let setIter = mySet[](); (()); // { value: 'apple', done: false } (()); // { value: 'banana', done: false } (()); // { value: 'cherry', done: false } (()); // { value: undefined, done: true }
📌 Set
Store in insertion order, iteratively returns unique values.
(2) Map
Iteration
let myMap = new Map([ ["name", "Alice"], ["age", 25] ]); for (let [key, value] of myMap) { (key, value); } // name Alice // age 25
📌 Map
Returns during iteration[key, value]
Array.
6. Iterator vs generator
characteristic | Iterator | Generator |
---|---|---|
How to create | Manual implementationnext()
|
function* Generate |
use
|
Need to be implemented manually | Generatorautomaticaccomplish |
Can pause execution | ❌ No | ✅ Yes (canyield ) |
Example: Generator
function* generatorFunction() { yield "A"; yield "B"; yield "C"; } let gen = generatorFunction(); (()); // { value: 'A', done: false } (()); // { value: 'B', done: false } (()); // { value: 'C', done: false } (()); // { value: undefined, done: true }
📌 The generator is simpler and supports ityield
Pause execution.
7. Iterator usage scenarios
7.1 Deconstruction Assignment
// When destructuring and assigning arrays and Set structures, the Iterator interface will be called by defaultlet set = new Set().add('a').add('b').add('c'); let [x, y] = set; // x='a'; y='b'
7.2 Extended operators
// The extension operator (...) also calls the default Iterator interfacelet str = 'hello'; [...str] // ['h', 'e', 'l', 'l', 'o'] let arr = ['b', 'c']; ['a', ...arr, 'd'] // ['a', 'b', 'c', 'd']
7.3 yield*
// yield* is followed by a traversable structure, which will call the traverser interface of the structurelet generator = function* () { yield 1; yield* [2, 3, 4]; yield 5; }; for (let v of generator()) { (v); } // 1, 2, 3, 4, 5
8. Things to note
8.1 for…of loop of object
// The object does not have the Iterator interface by default, and cannot be used directly for...oflet obj = { a: 1, b: 2, c: 3 }; for (let value of obj) { (value); // TypeError: obj is not iterable } // Correct way to traverse objects// 1. Use ()for (let key of (obj)) { (key + ': ' + obj[key]); } // 2. Use ()for (let [key, value] of (obj)) { (key + ': ' + value); }
8.2 Iterator interface and Generator function
// Implement the Iterator interface using Generator functionlet obj = { *[]() { yield 'hello'; yield 'world'; } }; for (let x of obj) { (x); } // hello // world
9. Best Practices
9.1 Deploy the Iterator interface for the class
class Collection { constructor() { = []; } add(item) { (item); } *[]() { for (let item of ) { yield item; } } } let collection = new Collection(); ('foo'); ('bar'); for (let value of collection) { (value); } // foo // bar
9.2 Asynchronous Iterator
// ES2018 introduces an asynchronous iteratorconst asyncIterable = { async *[]() { yield 'hello'; yield 'async'; yield 'iteration'; } }; (async () => { for await (const x of asyncIterable) { (x); } })(); // hello // async // iteration
10. Applicable scenarios
✅ Applicable to
Iterate through arrays, strings, Set, MapCustom iterable objectsStreaming data (similar to paging loading)Avoid loading of big data at one time (generator)
11. Summary
-
Iterator
is an interface provided by ES6 for sequential access to collections. -
Make an object iterable and available for
for...of
、spread
。Set
、Map
、Array
、String
Default implementation, can be iterated directly.
- Generator (
Generator
) Automatically create an iterator to pause execution (yield
), more powerful.
This is the article about the summary of the use of ES6 iterator. For more related content of Iterator, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!