ES6 Iterator and Generator

Catalog

One, Iterator

Two, Generator

Three, small exercises

IV. Author's Quotations

Since you know the distance, you'll have to start early from tomorrow.

One, Iterator

Definition:

An iterator is an interface that provides a unified access mechanism for various data structures. Any data structure can complete traversal by deploying the lterator interface. ES6 adds traversal for...of.

Data native to the lterator interface are Array, Arguments, Set, Map, String, NodeList.

Principle: Create a pointer object that points to the start of the data structure, calls==next()==method for the first time, automatically points to the first member of the data structure, and then calls next() continuously. The pointer moves backwards until it points to the last member. Next() is not called to return an object containing the value s and done properties.

For example: arr arrays, which themselves have iterators, use arr[symbol.iterator](); Come to this interface

The next () call returns an object containing the value done property, called once, with the pointer pointing once. If the call does not point to a class content, value returns undefined. done returns true to tell the interface that there is no value behind it

For of traversal iterates over data types. If you want to traverse objects through for of, you first think of iterators. You can create iterators for objects by manually customizing them, or you can traverse objects.

<script>
        const arr = ['Glory of Kings', 'Eat chicken', 'Alliance of Heroes']
        let mylterator = arr[Symbol.iterator]();//Array itself has an interface, get this interface
        console.log(mylterator.next());//{value:'Glory of the King', done: false}
        console.log(mylterator.next());//{value:'Eat chicken', done: false}
        console.log(mylterator.next());//  {value:'League of Heroes', done: false}
        console.log(mylterator.next());// {value: undefined, done: true}
        for(let value of arr){
console.log(value);
        }//King Glory Eats Chicken Heroes for of Traversing Iterable Data Types
    </script>

Application: Create iterators for object types by manually customizing them

 //Iterator interface usage, object type
        //Manually customize the creation of iterator interfaces for object types
        const Person = {
            title: 'web2209',
            student: ['Sun WuKong', 'Zhu Bajie', 'Sand Monk'],
            [Symbol.iterator]() {
                let i = 0;
                return {
                    next: () => {
                        if (i < this.student.length) {
                            const Obj = { value: this.student[i], done: false };
                            i++;
                            return Obj;
                        } else {
                            return { value: undefined, done: true }
                        }
                    }
                }
            }
        }
//Receive Interface
const myiterator=Person[Symbol.iterator]();//Receive Iterator
console.log(myiterator.next());//{value:'Monkey King', done: false}
console.log(myiterator.next());//{value:'Pig Eight Rings', done: false}*
console.log(myiterator.next());//{value:'Sha Monk', done: false
console.log(myiterator.next());//{value: undefined, done: true} has no value pointed to, returns undefined done as true
    </script>

 

Note: next () is followed by an arrow function, not a normal function. The reason here refers to the problem that this points to. Normal function points to the caller, so this cannot be used here. Otherwise, an error occurs. Instead, use an arrow function, which points to a static function. Depending on the context, how to define it can refer to my previous blog (this points to)

Two, Generator

Definition:

Generator itself is a special function. Generator function is an asynchronous programming solution provided by ES6, and its syntax behavior is different from traditional functions. Generator function* xxx(){}

 <script>
        function * read() {
            console.log('First Execution');
            yield 'Sami'
            console.log('Second Execution');
            yield 'Washing rice'
            console.log('Third Execution');
            yield 'Cook rice'
            console.log('Fourth Execution');

            yield 'Having dinner'
        }
        const myread=read();//Generator function that returns an iterator object that calls the function using next()
        console.log(myread.next());
        console.log(myread.next());
        console.log(myread.next());
        console.log(myread.next());
        console.log(myread.next());
      

    </script>

Generator Call

Execute the generator function, returning an iterator object through iterator.next() calls to execute the statement within the function, using the yield ed delimiter to make the statement execute in segments.

Generator parameters

Concept: The next('BBB') parameter is passed in as the return value of the last next method.

    <script>
        function* read(person) {
            console.log(person);
            console.log('First Execution');
            let a1 = yield 'Sami'
            console.log('Second Execution');
            let a2 = yield 'Washing rice'
            console.log('Third Execution');
            let a3 = yield 'Cook rice'
            console.log('Fourth Execution');
            let a4 = yield 'Having dinner'
        }
        const myread = read('Little Red');//Generator function that returns an iterator object that calls the function using next()
        console.log(myread.next());
        console.log(myread.next('a1'));
        console.log(myread.next('a2'));
        console.log(myread.next('a3'));
        console.log(myread.next('a4'));
    </script>

Note: Generator defaults to Symbol. The iterator property is assigned, so all iterators created by the generator are iterators. The first time the next() method is called, any parameters passed in are discarded. Since the parameters passed to the next () method will replace the return value of the last yield and no yield statement will be executed before the next () method is called for the first time, it is pointless to pass parameters on the first call to the next () method.

Three, small exercises

<body>
    <div class="box">
        <P id="load"></P>
        <p id="message"></p>
        <button id="btn">Loading data</button>
    </div>
    <script>
        let load = document.getElementById('load');
        let message = document.getElementById('message');
        let btn = document.getElementById('btn');
        function step1() {
            setTimeout(() => {
                load.innerHTML = 'Data loading......'
                getinfo.next();
            }, 2000)
        }
        function step2() {
            setTimeout(() => {
                message.innerHTML = 'It looks like it's disconnected'
                getinfo.next();
            }, 2000)
        }
        function step3() {
            load.innerHTML = '';
            //   getinfo.next();
        }
        //generator
        function* info() {
            let first = yield step1();

            let two = yield step2();

            yield step3();
        }
        const getinfo = info();//Execute generator function, returning an iterator object
        //Click to load
        btn.addEventListener('click', () => {
            getinfo.next();//call
        })
    </script>
</body>

 

 

IV. Author's Quotations

Since you know the distance, you'll have to start early from tomorrow.

Tags: ECMAScript Front-end

Posted by katlis on Mon, 18 Jul 2022 23:05:30 +0530