当前位置:网站首页>Iterator, generator generator details

Iterator, generator generator details

2022-06-12 12:33:00 Fashion_ Barry

Talking about Generator( generator ) Before , Let's first understand another concept , iterator

One 、 iterator Iterator

iterator Iterator yes ES6 A new traversal mechanism is introduced , It is also a special object , It has some proprietary interfaces designed specifically for iterative processes ;

Each iterator object There is one. next() Method , Each call will return a current result object .

There are two properties in the current result object :

        1.value:  The value of the current property

        2.done:  Used to determine whether traversal ends , When there is no more data to return , return true

        Every call next() Method , Will return the next available value , Know that the traversal is over .

Two 、 generator Generator

A generator is a function that returns an iterator , adopt function  After the keyword ( * ) To express , New keywords will be used in functions yield . The asterisk can be next to function keyword , You can also add a space in the middle .

function* generator(){
    const list = [1,2,3];
    for(let i of list){
        yield i
    }
}

let g = generator();

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

  3、 ... and 、 characteristic

1. Every time I finish one yield The function will automatically stop running after the statement , Until it's called again next();

2. yield Keywords can only be used in generators (Generator) For internal use , Using it elsewhere causes the program to throw an error ;

3. You can use function expressions to create generators , But you can't use the arrow function

The most common place is in stream When processing data streams , Iterators are used !

 

 

 

 

原网站

版权声明
本文为[Fashion_ Barry]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010519592363.html