当前位置:网站首页>JS advanced programming version 4: generator learning

JS advanced programming version 4: generator learning

2022-06-23 20:23:00 51CTO

JavaScript Advanced programming section 4 edition ( Hereinafter referred to as elevation 4), Compared with the second 3 edition , Added ES6 to ES10 New content of , Deleted old and outdated content , And enrich more detailed content on the original basis .

Translated into Chinese on 2020 Sold in , Proper “ Fresh out ”, If you ask Ben Gua : Current school JavaScript Na Jiaqiang , I can only say : Red Treasure Book No 4 Version is the best .

So , Take the opportunity of more culture , This melon will open a small series , Take you through advanced programming again 4( I was just jumping and watching ), Will extract essence , In the simplest words 、 Try to grasp the overall situation 、 While going through it quickly , Record and share with the workers ~~

JS Advanced programming section 4 edition : Generator learning _ generator

Text

generator , To put it bluntly , Is to customize the generation : Of iterator objects .

      
      
class Counter {
// Counter The instance of should iterate limit Time
constructor(limit) {
this.count = 1;
this.limit = limit;
}
next() {
if (this.count <= this.limit) {
return { done: false, value: this.count++ };
} else {
return { done: true, value: undefined };
}
}
[Symbol.iterator]() {
return this;
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

Create iterators in this way , It's too hard , And this is just a simple version , Multiple iterations are not yet supported , Support multiple iterations , You will also use the closure structure :

      
      
class Counter {
constructor(limit) {
this.limit = limit;
}
[Symbol.iterator]() {
let count = 1,
limit = this.limit;
return {
next() {
if (count <= limit) {
return { done: false, value: count++ };
} else {
return { done: true, value: undefined };
}
}
};
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

therefore , The generator came into being .

      
      
function* generatorFn() {
return 'foo';
}

const g = generatorFn();
console.log(g === g[Symbol.iterator]()); // true
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

You can see :

​g === g[Symbol.iterator]()​​ by true, Proper , The generator is the best proof to construct iterator objects !!

Let's see how the generator function is written :

      
      
// Generator function
function* generator(i){
yield i + 1
var y = yield 'foo'
yield y
}

var iterator = generator(10) // At this time, the generator function does not execute , Returns an iterator

iterator.next() // {value: 11, done: false}
iterator.next() // {value 'foo', done: false}
iterator.next(10) // {value: 10, done: false}, take 10 Assign to the previous yield 'foo' The value on the left side , namely y = 10, return y
iterator.next() // {done: true}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

The syntax rules for generator functions are :

Calling a generator function does not immediately execute the statements in it , Instead, it returns a iterator (iterator) object .

When this iterator's next() The method was first ( follow-up ) Invocation time , The statements in it are executed to the first ( follow-up ) appear yield Up to ,yield Followed by the value to be returned by the iterator .

Or if you use yield*( There's an extra asterisk ), It means to transfer the execution right to another generator function ( The current generator is paused ). call next() When the method is used , If parameters are passed in , Then this parameter will be executed as the previous one yield The return value of the statement .

Actually , Just put yield Understood as a reduced version of return that will do ; Every execution of a next, Just return A value , If there is an assignment , It is assigned to the previous one return Results go inside .

Summary

Summary of the last paragraph in Chapter 7 of elevation , Every word is worth reading carefully :( Suggest reciting )


iterator Is an interface that can be implemented by any object , Support continuous access to each value of object output .


Any implementation Iterable Interface objects all have a Symbol.iterator attribute , This property refers to the default iterator . The default iterator is like an iterator factory , That's a function , After the call, an implementation is generated Iterator Object of the interface .

Iterators must be called continuously next() Method to get values continuously , This method returns a IteratorObject. This object contains a done Properties and a value attribute . The former is a Boolean value , Indicates whether there are more values to access ; The latter contains the current value returned by the iterator . This interface can be called manually and repeatedly next() How to consume , It can also be done through native consumers , such as for-of Cycle to consume automatically .


generator It's a special function , A generator object is returned after the call . The generator object implements Iterable Interface , So it can be used anywhere you consume an iteratable object .


What's unique about generators is that they support yield keyword , This keyword can pause the execution of generator functions . Use yield Keywords can also be accessed through next() Methods receive input and generate output . After adding the asterisk ,yield Keyword can serialize the iteratable object following it into a series of values .


OK, The above is the sharing of this article . Think it's good. Give it a compliment , Your encouragement , My motivation , Adhere to the original quality of good articles ~~ Feel free to leave a comment I'm Anthony nuggets , The output exposes the input , Technical insight into life . Goodbye ~~

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231833089998.html