Iterator traverser / Generator of ES6 new features

Catalogue

(1) Iterator iterator

(2) Generator

(1) Iterator iterator

Traversal is an interface that provides a unified access mechanism for different data structures.  

If a data structure has an ergodic interface, the members of the data structure can be processed in turn.  

At present, there are four data structures used by javascript to represent a Set, namely array, object, Set and Map, and these four data structures can be nested with each other. For example, the members of an array can be objects, and the members of an object can be sets.

I Traverser interface:

If a structure has symbol Iterator attribute, then the data structure is said to have an iterator interface.

Symbol. The iterator returns the iterator property of the symbol object, which is a predefined special value of type symbol.

Symbol. The iterator property points to a method. Calling this method returns an iterator object, which is a pointer object and points to the starting position of the data structure by default.

let arr = ["Source library network", 4, "www.yuankuwang.com", "Peking University"];

let it = arr[Symbol.iterator]();

console.log(it.next());

console.log(it.next());

console.log(it.next());

//Funny traversal

let arr = ["Source library network", 4, "Peking University"];

let it = arr[Symbol.iterator]();

//Circulator (high efficiency)

for(;;) {

let nextEle = it.next();

if(nextEle.done) {

break

}

console.log(nextEle.value);

}

//Each call to the next() method will return an object containing the value and done attributes. The value attribute value is the value of the data structure member. If the traversal is completed, the value attribute value is undefined; The done attribute is a Boolean value. If it is true, the traversal is completed. If it is false, the traversal has not been completed

II By default, it has the data structure of the ergodic interface, and the for of loop

When a for of loop is used to traverse a data structure, the traverser interface will be called automatically.

In ES6, there are four types of data structures with ergodic interfaces by default:

(1) Array

(2) Some class arrays

(3)Map

(4)Set

var arr = [1,2,3,'aa','bb','cc'];

for(let elem of arr) {

  console.log(elem);

}

Some class arrays: 

let obj = {

  data: ["aa","bb",'cc',3,9,8],

  [Symbol.iterator]() {

    const self = this;

    let index = 0;

    return {

      next() {

        if (index < self.data.length) {

          return {

            value: self.data[index++],

            done: false

          };

        } else {

          return { value: undefined, done: true };

        }

      }

    };

  }

};

let it = obj[Symbol.iterator]();

console.log(it.next().value)

3, Expand operator:

If a data structure has an ergodic interface, you can use the expansion operator in addition to the for of loop.

Code examples are as follows:

let arr = ["Source library network", 4, "www.yuankuwang.com"];

console.log(...arr);

(2) Generator

Generator function is a new asynchronous programming scheme in ES6.

Note: the Generator function refers to a new syntax structure. It is an ergodic object Generator. It can encapsulate multiple states, which is very suitable for asynchronous operation.

[grammar]

The syntax of Generator function is similar to that of ordinary function function, but there are three differences:

(1) There is an asterisk (*) between the function keyword and the function name.

(2) You can use the yield statement in the function body.

(3) The function will not be executed immediately after it is called, but an ergodic object is returned.

//A Generator function

function* yuanku() {

  yield "Source library network";

  yield "Haidian, Beijing";

  yield "www.yuankuwang.com";

  return "end";  

}

//Inside the function, use the yield statement to define different states. return can also define a state, that is, the above code has four states

var y = yuanku(); //Calling this function does not immediately execute its code, but returns an iterator object

console.log(y.next()); //Returns an object with value and done attributes

console.log(y.next()); //If there is a return, return {value:end,done:true}; If there is no return, {value: undefined, done: true}

yield statement:

Each yield statement defines a different state, which is also a code execution pause identifier.

The yield statement cannot be used in ordinary functions, otherwise an error will be reported.

Calling the Generator function can return an ergodic object. To access each state in the Generator function, you need to use the ergodic object to call the next() method.

If the yield statement is a part of other statements, it must be wrapped in parentheses, otherwise an error will be reported

function *yuanku() {

  //console.log("welcome to" + yield "source library network")// report errors

  console.log("Welcome to" + (yield "Source library network"));//correct

}

  let y = yuanku();

  console.log(y.next().value); //Return to yield first

  console.log(y.next().value); //return,yield is undefined

next() method:

One of the main functions of next() is to continue the execution of the next piece of code from the suspended state.

Another important function of next() is that it can accept a parameter as the return value of the previous yield statement.

Although the value of the expression behind the yield statement can be used as the value attribute value of the object when the code is executed to the yield statement, by default, the yield statement has no return value, or its return value is undefined

Note: the return value of the yield statement and the return value of the expression after yield are two concepts

Pass the value to next,!!! This value is used as the return value of the previous yield!!!

function* yuanku(num) {

      let x = 2 * (yield num);

      console.log('x='+x);

      let y = yield x*3;

      console.log('y='+y);

      console.log(x,y);

    }

    var g=yuanku(5);

    console.log(g.next());//{value:5,done:false}, the first next pass is meaningless because there is no previous yield

    console.log(g.next());//x=NaN {value:NaN,done:false}

    console.log(g.next(3));//{value:12,done:false}

    console.log(g.next(3));//{value:undefined,done:true}

//-----------Asynchronous method measurement-------------------------

setTimeout(function () {

    console.log("hello");

  },3000);



let y;

   var func = function(time) {

      setTimeout(function() {

          console.log(time, "  on");

          y.next(true);

      }, time);

    };

    var gen = function * () {

        var f1 = yield func(3000);

        console.log('f1:', f1);

        var f2 = yield func(1000);

        console.log('f2:', f2);

    };

    y = gen();

    y.next();

console.log('end');

 

Tags: Vue Javascript ECMAScript

Posted by Varma69 on Thu, 14 Apr 2022 10:29:21 +0930