当前位置:网站首页>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 ~~

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 .
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 ~~
边栏推荐
- ZABBIX monitoring - Aruba AP operation data
- JS高级程序设计第 4 版:生成器的学习
- 好用的人事管理软件有哪些?人事管理系统软件排名!
- Are internal consultants and external consultants in SAP implementation projects difficult or successful?
- Kinsoku Jikou Desu Sina stock interface change
- Is it safe to make new debt
- RStudio 1.4软件安装包和安装教程
- Want to open an account, is it safe to open an account on the stock Internet? Will the funds be cheated away?
- LeetCode 260. Number III that appears only once
- Naacl 2022 finds | byte proposes MTG: multilingual text generation data set
猜你喜欢
Implementing MySQL fuzzy search with node and express

35 year old crisis? It has become a synonym for programmers

After the collapse of UST, will the stable currency market pattern usher in new opportunities?

JDBC 在性能測試中的應用

TCP/UDP基本原理

直播分享| 腾讯云 MongoDB 智能诊断及性能优化实践

图扑软件数字孪生智慧水务,突破海绵城市发展困境

如何避免基因领域“黑天鹅”事件:一场预防性“召回”背后的安全保卫战

Add two factor authentication, not afraid of password disclosure, let alone 123456

Why is only one value displayed on your data graph?
随机推荐
墨天轮访谈 | IvorySQL王志斌—IvorySQL,一个基于PostgreSQL的兼容Oracle的开源数据库
如何利用数仓创建时序表
国元期货交易软件正规吗?如何安全下载?
活动报名 | MongoDB 5.0 时序存储特性介绍
I came from a major, so I didn't want to outsource
金鱼哥RHCA回忆录:DO447管理用户和团队的访问--用团队有效地管理用户
5 月最大的 GameFi 崩溃受害者能否在熊市中生存?| May Monthly Report
Syntaxe des requêtes fédérées SQL (inline, left, right, full)
深入理解和把握数字经济的基本特征
Ugeek's theory 𞓜 application and design of observable hyperfusion storage system
ZABBIX monitoring - Aruba AP operation data
Yaokui tower in Fengjie, Chongqing, after its completion, will be the safety tower for Sichuan river shipping with five local scholars in the company
火线沙龙第26期-多云安全专场
Interpreting the 2022 agile coaching industry status report
Save: software analysis, verification and test platform
Development notes of wedding studio applet based on wechat applet
Implementing MySQL fuzzy search with node and express
SAP实施项目上的内部顾问与外部顾问,相互为难还是相互成就?
「开源摘星计划」Containerd拉取Harbor中的私有镜像,云原生进阶必备技能
vs2022scanf函数的使用,使用scanf的报错-返回值被忽略:解决·方法