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 implement ES6 iterator

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the knowledge of "how to implement ES6 iterator". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Iterator is a new traversal mechanism introduced by ES6. Iterator has two core concepts: iterator is a unified interface, its function is to make all kinds of data structures accessible conveniently, it is realized by a method whose key is Symbol.iterator.

Iterators are pointers used to traverse data structure elements (such as cursors in a database).

Iterator

Iterator is a new traversal mechanism introduced by ES6. Iterators have two core concepts:

Iterator is a unified interface, its role is to make a variety of data structures can be easily accessed, it is through a key Symbol.iterator method to achieve.

Iterators are pointers used to traverse data structure elements (such as cursors in a database).

Iterative process

The iterative process is as follows:

Create an iterator through Symbol.iterator that points to the starting position of the current data structure

Then iterate down to the next location through the next method, and the next method returns the object at the current location, which contains two attributes: value and done. Value is the value of the current property, and done is used to determine whether the traversal is over.

Traversal ends when done is true

The following is illustrated by a simple example:

Const items = ["zero", "one", "two"]; const it = items [Symbol.iterator] (); it.next (); > {value: "zero", done: false} it.next (); > {value: "one", done: false} it.next (); > {value: "two", done: false} it.next (); > {value: undefined, done: true}

In the above example, first create an array, then create an iterator through the Symbol.iterator method, and then repeatedly call the next method to access the internal items of the array, ending when the property done is true.

Iterators are part of protocols (rules that use them) and are used for iterations. A key feature of the protocol is that it is sequential: the iterator returns one value at a time. This means that if the iterable data structure is nonlinear (such as a tree), the iteration will linearize it.

Iterable data structure

The following values can be iterated:

Array

String

Map

Set

Dom element (in progress)

We will use the for...of loop (see for...of loop below) to iterate over the data structure.

Array

Arrays (Array) and array of types (TypedArray) they are iterable.

For (let item of ["zero", "one", "two"]) {console.log (item);} / output:// zero// one// twoString

Strings are iterable, but they traverse Unicode codes, each of which may contain one or two Javascript characters.

For (const c of'z\ uD83D\ uDC0A') {console.log (c);} / / output:// zplink /\ uD83D\ uDC0A

Map

Map is mainly about iterating their entries, each entry is encoded as an item of [key, value], and entries iterates in the same order as the added one.

Const map = new Map (); map.set (0, "zero"); map.set (1, "one"); for (let item of map) {console.log (item);} / / output:// [0, "zero"] / / [1, "one"]

Note: WeakMaps cannot be iterated

Set

Set iterates over its elements in the same order in which they are added

Const set = new Set (); set.add ("zero"); set.add ("one"); for (let item of set) {console.log (item);} / / output:// zero// one

Note: WeakSets cannot be iterated

Arguments

Arguments is currently less and less used in ES6, but it is also traverable.

Function args () {for (let item of arguments) {console.log (item);}} args ("zero", "one"); / / output:// zero// one

Ordinary objects can not be iterated

Normal objects are created by object and cannot be iterated:

/ / TypeErrorfor (let item of {}) {console.log (item);}

For...of cycle

For...of is a new loop introduced by ES6 to replace for..in and forEach () and supports a new iterative protocol. It can be used to iterate over regular data types, such as Array, String, Map, Set, and so on.

Iterate over regular data types

Array

Const nums = ["zero", "one", "two"]; for (let num of nums) {console.log (num);} TypedArrayconst typedArray1 = new Int8Array (6); typedArray1 [0] = 10 new Int8Array Array 1 [1] = 11; for (let item of typedArray1) {console.log (item);}

String

Const str = "zero"; for (let item of str) {console.log (item);}

Map

Let myMap = new Map (); myMap.set (0, "zero"); myMap.set (1, "one"); myMap.set (2, "two"); / / traversing key and valuefor (let [key, value] of myMap) {console.log (key + "=" + value);} for (let [key, value] of myMap.entries ()) {console.log (key + "=" + value) } / / only traverse keyfor (let key of myMap.keys ()) {console.log (key);} / / only traverse valuefor (let value of myMap.values ()) {console.log (value);}

Set

Let mySet = new Set (); mySet.add ("zero"); mySet.add ("one"); mySet.add ("two"); / / traversing the entire setfor (let item of mySet) {console.log (item);} / / only traversing the key value for (let key of mySet.keys ()) {console.log (key);} / / traversing only valuefor (let value of mySet.values ()) {console.log (value) } / / traverse key and value, which will be equal to for (let [key, value] of mySet.entries ()) {console.log (key + "=" + value);}

Iterable data structure

The of Operand must be iterable, which means that if it is a normal object, it cannot be iterated. If the data structure is similar to that of an array, you can use the Array.from () method to iterate through the transformation.

Const arrayLink = {length: 2,0: "zero", 1: "one"} / / report TypeError exception for (let item of arrayLink) {console.log (item);} / / normal operation / / output:// zero// onefor (let item of Array.from (arrayLink)) {console.log (item);}

Let, const, and var for for..of

If you use let and const, a new storage space is created for each iteration, which ensures that the scope is within the iteration.

Const nums = ["zero", "one", "two"]; for (const num of nums) {console.log (num);} / report to ReferenceErrorconsole.log (num)

As we can see from the above example, the last sentence will report an exception. The scope of the num is only inside the loop body and is not valid externally. For more information, please see the let and const sections. This will not happen with var because var acts globally and iterations will not create a new storage space each time.

Const nums = ["zero", "one", "two"]; forv (var num of nums) {console.log (num);} / / output: twoconsole.log (num); that's all for "how to implement the ES6 iterator". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Database

Wechat

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

12
Report