What is iterator ?
iterator (iterator) It is a special function for the browser to easily traverse regular objects . Yes ! It's a function .
For the time being, no matter how this function is implemented , I believe you are familiar with the following code :
The reason arr Can pass for of Print out a standing ,b standing , Because the array prototype chain contains such an iterator function , We go through Symbol.iterator This special type to get the following :
[native code] It means to browse its native implementation , Code that has been compiled into processor specific machine code , Optimized processing , Its operation efficiency is high .
You can see , Both the array and the prototype chain contain this name by values Function of , You can find the array arr The iterator functions of are all equal to Array Iterator function on prototype chain , Students who have studied prototype chain inheritance often understand .
Similarly, , stay ES6 Newly added Map、Set Objects have the shadow of iterators , We can also use for of Functions iterate over their instances :
natural , They also have their own iterator functions :
Fit expansion operator (...) Use , Please pay attention to the printed content :
thus it can be seen , If an object contains iterator functions (iterator) So it's an iterative object , It can be used for of perhaps ... Extension operators .
for of How to get the internal elements one by one ?
The answer is by calling next Method , The instance returned by calling the iterator function ( object ) Of next Method :
Every time you call next Get a value , When you getdoneStatus astruewhen , End of call
How to implement an iteratable object by yourself ?
Please look at the code. :
- The key 1:iterator The function must return a value containing
nextObject of property . - The key 2:next Property is a method , And must return an object
{value:'value',done:true/false }.value Represents the value returned by each iteration ,done Determines whether the iteration ends . If done For ever true, Then iterations will never stop .
What is? Generator?
Generator It's an object , By Generator function (generator function) Back to , And it matches Iterative protocol and iterator protocol .
generator function A function is to add a... Before the name of an ordinary function * Number , And the function uses yeild Keywords define function breakpoints , Let the function execute in batches from top to bottom and return the value .
since myGenerator Examples can use for of To iterate , Does he look like Array Like an array iterator Function? ? We use it [Symbol.iterator] Property values :
It is as expected , Generated by the generator function generator Objects have iteratable functions .
Use Generator reinventing iterableObj
Before transformation :
After transformation :
Use generator, Let asynchronous code execute like synchronous code
Promise Appearance , Let programmers say goodbye to the painful callback hell , Write asynchronous code like this :
Coding is comfortable , But there are more comfortable positions :
The function is written , however *getData() How to call a function ? Let's have a look
We found that , adopt next() When a function is called iteratively , Back to value yes promise, It's not what you want to do after execution 1,2,3, So we can call then Method to get Assertion After the value of , Look at the following code :
In the code, we pass promise Chain call mode , Ensure that the last request is completed before proceeding to the next next Call to . It should be noted that , Print for the first time value1 after , Need to value1 As The next time call next Parameters of , otherwise DataA What you get is undefined.
Careful friends have noticed , stay getData Generator function yeild Keywords appear 3 Time , however next Called 4 Time , Why not a yeild Corresponding to one next Well ?
yeild It's like a knot on a rope , A piece of The rope is divided into Two halves It only needs One junction , That is, the left part and the right part . It is known that there is... On a rope 3 individual junction , The rope is divided into A few part ? All the students taught by PE teachers know that 4.
generator Call is actually executed according to the law next Method , Take the result of the last execution as next The parameters of the function . Then encapsulate a function to execute automatically generator example , You don't have to write a pile of code at a time to call next.
How to make generator Automatic execution , How to package ?
Encapsulate a function , Put the generator function getData As a parameter , Recursively call next Method , For a brief code, please see :
In fact, the famous co The library used a similar method in the early days , Of course co The framework also takes into account other very complex situations , For example, abnormal error .
async await coming
async await Syntax sugar is to facilitate asynchronous programming and write code like synchronous programming , no need co library , Just add... Before the function async The identifier represents the generator function , use await replace yeild key word . Don't think about generator How instance calls next The method . It's so delicious !
Summary :
- We learned the basic concept of iterators , got it
Array、Map、SetThere are iterators in the prototype chain , Can pass[Symbol.iterator]visit . - You know the properties of the iterator object , contain next Method , And the method must return
valueanddoneattribute . Finally, give an ordinary{}object , Added their own implementationiterator, Let it pass through for of Iterative execution . Genetatoryes es6 New objects introduced in , Cannot instantiate directly , You need to pass the generator function ( Add... Before the function name *) return .iteratorIterate over objects andgeneratorExamples are the samenextMethod iteration . Finally throughGenetatorThe new grammar rewritesiterator, achievefor ofThe purpose of traversal .- I encapsulated something similar
coFunction of module , Let the iterator automatically execute , Make it possible to write asynchronous code synchronously . - es7 Of
asyncandawaitSyntax sugar makes asynchronous methods and writing simpler and easier .
The articles :
Experience summary of developing wechat applet ,UI Components 、 Chart 、 Customize bar All finish
Please don't forget to give me give the thumbs-up 、 Comment on 、 Collection . Please. !

![H5 native player [learn video]](/img/51/83a200d0423b7274d1e981ec2ede2c.jpg)






![The k-th node of the binary search tree [sword finger offer]](/img/9c/26b508100d8b49c114cf72346a8e7c.jpg)
