Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand and master iterators in ES6

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to understand and master iterators in ES6". In daily operation, I believe many people have doubts about how to understand and master iterators in ES6. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to understand and master iterators in ES6"! Next, please follow the editor to study!

In addition to Array in JavaScript, ES6 also adds Map and Set structures. When we need to manipulate these data, we need a unified interface to deal with these different data structures. The newly added Iterator (iterator) in ES6 provides such a mechanism.

Data structures supported by Symbol.iterator

The Symbol.iterator method is provided in ES6, which returns an iterator object. Currently, Array, Set, and Map data structures have Symbol.iterator properties by default. As shown below, you can see that the Object type is not available.

Console.log ([] [Symbol.iterator] ()); / / Object [Array Iterator] {} console.log ((new Map ()) [Symbol.iterator] ()); / / [Map Entries] {} console.log ((new Set ()) [Symbol.iterator] ()); / / [Set Iterator] {} console.log ({} [Symbol.iterator]); / / undefined

In addition to these data structures mentioned above, some array-like objects in JavaScript also have Symbol.iterator properties by default, such as strings, arguments objects, and DOM's NodeList objects.

String

Const str = 'nodejs'; console.log (str[ Symbol.iterator] ()); / / Object [String Iterator] {} for (const val of str) {console.log (val); / / nodejs}

Arguments object

Function print () {console.log (arguments [Symbol.iterator] ()); / / Object [Array Iterator] {} for (const val of arguments) {console.log (val); / / n o d e}} print ('nasty,' oval, 'dumped,' e')

DOM NodeList object

Const divNodeList = document.getElementsByTagName ('div') console.log (divNodeList [Symbol.iterator] ()) / Array Iterator {} for (const div of divNodeList) {/ / outputs each div tag console.log (div);}

Next method of iterator object

Calling the Symbol.iterator method of an iterable object returns an iterator object with a next method in its interface that returns two properties, value and done, where the value property is the value of the current member and the done property indicates whether the traversal ends. Understanding the generator function (Generator) may be familiar, and you will get an iterator object when you execute a generator function, but it is not a concept to distinguish between a generator and an iterator.

Const arr = ['Symbol.iterator,' console.log,'e']; const iterator = arr [Symbol.iterator] (); console.log (iterator.next ()); / / {value: 'nasty, done: false} console.log (iterator.next ()); / / {value:' oval, done: false} console.log (iterator.next ()); / / {value: 'dumped, done: false} console.log (iterator.next ()) / / {value: 'eBay, done: false} console.log (iterator.next ()); / / {value: undefined, done: true}

In the above example, an array arr is declared, an iterator object iterator is created by calling the Symbol.iterator method of arr, and then the next method is called to return the contents of the current array until the next method returns a value of true.

Iterator interface traversal

Deconstruction assignment

The Symbol.iterator method is called by default when the array, Set, and Map deconstruct the assignment. Notice that Map returns an entries method when calling the Symbol.iterator method, which returns a new iterator object and contains the [key, value] array of each element in the Map object in insertion order, so calling the keys or values method of the Map instance also returns a new iterator object.

Const set = new Set (). Add ('n'). Add ('o'); const map = new Map (). Set ('d'). Set ('e'); const [xSet, ySet] = set; console.log (xSet, ySet) / / n o const [xMap, yMap] = map.keys (); console.log (xMap, yMap) / / d e

Extension operator

Extension operator (...) in ES6. The Symbol.iterator methods of array, Set, Map, and other structures are also called by default.

Const set = new Set ('node'); const [x, y,... z] = set; console.log (x, y, z); / / no [' dudes,'e']

For...of cycle

ES6 introduces for...of loop from C++, Python and other languages, and the Symbol.iterator method is also called inside the loop, as long as the data structure with Iterator interface can be used.

Const set = new Set (). Add ('n'). Add ('o'); for (const val of set) {console.log (val);}

The for...of loop can also use break; to interrupt the execution of the iterator during execution. The following example modifies the loop statement to execute break after the first execution of val equals n.

For (const val of set) {console.log (val); / / n if (val ='n') break;}

Other methods

The array supports the Iterator interface by default, so any method that accepts the array as a parameter will also call the Symbol.iterator method by default, as shown below:

Const set = new Set (). Add ('n'). Add ('o'); console.log (Array.from (set)); / / ['n','o'] Promise.all (set). Then (val = > console.log (val)) / / ['n','o'] Promise.race (set). Then (val = > console.log (val)) / / n

Custom iterator

Iterative protocol

According to the iterable protocol, to become an iterable object, you must first have a * * @ @ iterator * *, that is, (Symbol.iterator) property, which is a function with no parameters and returns an object that conforms to the iterator protocol.

According to the iterator protocol, the iterator object is defined to return a next () method, and the next () method returns an object that contains value and done properties.

Const myIterator = {/ / for...of loop uses [Symbol.iterator]: function () {return this}, / / standard iterator interface method next: function () {/ /...}}

If you write it in TypeScript, it is described as follows:

/ / Ergographer interface Iterable interface Iterable {[Symbol.iterator]: Iterator} / / Iterator object interface Iterator {next (value?: any): IterationResult,} / next method returns a value definition interface IterationResult {value: any, done: boolean}

Implementation of iterator based on ordinary function

The function implementation of an iterator can be either an ordinary function or a generator function. We first take the ordinary function as an example and define a Range constructor that is used to output all the values of the two numerical regions.

Function Range (start, end) {this.id = start; this.end = end;} Range.prototype [Symbol.iterator] = function () {return this} Range.prototype.next = function next () {if (this.id > this.end) {return {value: undefined, done: true}} return {value: this.id++, done: false} const R1 = new Range (0,3) Const it = R1 [Symbol.iterator] () for (const id of R1) {console.log (id); / / 0meme 1jue 2jue 3}

Implementation of iterator based on generator function

The implementation using the generator function (Generator) is the easiest, as long as you use the yield statement to return the value of each time. As follows:

Range.prototype [Symbol.iterator] = function* () {while (this.id)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report