当前位置:网站首页>Iterator and for of.. loop
Iterator and for of.. loop
2022-07-07 15:41:00 【When can Xiaobai advance to success】
One 、Iterator
1、Iterator( Iterator ) The concept of
Iterator Iterator It's an interface , Provide unified access mechanism for different data structures . Any data structure , As long as the deployment Iterator Interface , You can complete the traversal operation .
Iterator The function of 3 individual :
- Provide a unified framework for all kinds of data structures 、 Simple access interface ;
- Enables members of a data structure to be arranged in a certain order ;
- ES6 Creates a new traversal command ---for...of loop ,Iterator Main interface supply for...of consumption ;
Iterator The traversal process of is as follows :
- Create a Pointer object , Point to the start of the current data structure . That is, the traverser object is essentially a pointer object .
- The first call to the next Method , You can point a pointer to the first member of a data structure .
- The second call to the next Method , You can point the pointer to the second member of the data structure .
- ...... ......
- Calling the pointer object's next Method , Until it points to the end of the data structure .
Every time you call next Methods will return the information of the current member of the data structure . That is, return a containing value and done Objects with two properties . among ,value Property is the value of the current member ,done Property is a Boolean value indicating whether the traversal ends .
2、 Case study
function main() {
var it = makeIterator(['a','b','c','d']);
for(let i=0;i<5;i++)
{
let re = it.next();
console.log("value:"+re.value+",done:"+re.done);
}
}
function makeIterator(array){
var nextIndex =0;
return {
next:function(){
return nextIndex<array.length?
{value:array[nextIndex++],done:false}:{value:undefined,done:true};
}
};
}Execution results :

The above case defines a makeIterator function , It's a traverser generator function , The function is to return an iterator object . An array ['a','b','c','d'] Execute this function , Will return the of the array Traverser object ( Pointer object )it.
3、 Default Iterator Interface
ES6 Some data structures of are native Interator Interface , That is, it can be for...of... Loop traversal . The reason lies in , These data structures are deployed natively Symbol.iterator attribute , All deployed Sysbol.iterator The data structure of the property is called the deployed iterator interface . Calling this interface will return an iterator object .
Original possession Iterator The data structure of the interface is as follows :
- Array、Map、Set、String、TypeArray、 Functional arguments object 、NodeList object
let arr =['a','b','c'];
let iter = arr[Symbol.iterator]();// Returns the traverser object , The traverser object has value and done Two attributes
for(let i=0;i<3;i++)
{
console.log(iter.next().value);
}Two 、for...of.. loop
for...of The loop can automatically traverse Generator Function generated Iterator object , And there is no need to call next Method .
function main() {
for(let v of DayGenerator())
{
console.log(v);
}
}
function* DayGenerator()
{
yield 'Sunday';
yield 'Monday';
yield 'Tuesday';
yield 'Wednesday';
yield 'Thursday';
yield 'Friday';
return 'Saturday';
}Running results :

once next Method of the return object done The attribute is true,for...of The cycle will end , And does not include the return object , So the top return Statement returned Saturday Not included in for...of In circulation .
except for...of loop , Extension operator (...)、 Deconstructing assignments and Array.from All calls inside the method are iterator interfaces . It means , They can all put Generator Function return Iterator Object as parameter .
function main() {
// Extension operator
console.log([...DayGenerator()]);
//Array.frome Method
console.log(Array.from(DayGenerator()));
// Deconstruct assignment
let [x,y,z]=DayGenerator();
console.log([x,y,z]);
//for...of loop
for(let v of DayGenerator())
{
console.log(v);
}
}
function* DayGenerator()
{
yield 'Sunday';
yield 'Monday';
yield 'Tuesday';
yield 'Wednesday';
yield 'Thursday';
yield 'Friday';
return 'Saturday';
}Running results :

边栏推荐
- Starting from 1.5, build a microservice framework link tracking traceid
- 居然从408改考自命题!211华北电力大学(北京)
- How to create Apple Developer personal account P8 certificate
- 有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
- Ctfshow, information collection: web8
- Webgl texture
- Ctfshow, information collection: web13
- [server data recovery] data recovery case of raid failure of a Dell server
- Typescript release 4.8 beta
- [quick start of Digital IC Verification] 29. Ahb-sramc (9) (ahb-sramc svtb overview) of SystemVerilog project practice
猜你喜欢

【数字IC验证快速入门】23、SystemVerilog项目实践之AHB-SRAMC(3)(AHB协议基本要点)

【数字IC验证快速入门】29、SystemVerilog项目实践之AHB-SRAMC(9)(AHB-SRAMC SVTB Overview)

什么是数据泄露

Qu'est - ce qu'une violation de données

Cocos creator collision and collision callback do not take effect

Ctfshow, information collection: web8
![[quick start of Digital IC Verification] 20. Basic grammar of SystemVerilog learning 7 (coverage driven... Including practical exercises)](/img/d3/cab8a1cba3c8d8107ce4a95f328d36.png)
[quick start of Digital IC Verification] 20. Basic grammar of SystemVerilog learning 7 (coverage driven... Including practical exercises)

知否|两大风控最重要指标与客群好坏的关系分析

How to create Apple Developer personal account P8 certificate

Starting from 1.5, build a microservice framework link tracking traceid
随机推荐
从 1.5 开始搭建一个微服务框架链路追踪 traceId
[understanding of opportunity -40]: direction, rules, choice, effort, fairness, cognition, ability, action, read the five layers of perception of 3GPP 6G white paper
Basic knowledge sorting of mongodb database
[deep learning] image hyperspectral experiment: srcnn/fsrcnn
如何在opensea批量发布NFT(Rinkeby测试网)
Guangzhou Development Zone enables geographical indication products to help rural revitalization
PAT 甲级 1103 Integer Factorizatio
[deep learning] semantic segmentation experiment: UNET network /msrc2 dataset
[markdown grammar advanced] make your blog more exciting (IV: set font style and color comparison table)
一大波开源小抄来袭
Cocos makes Scrollview to realize the effect of zooming in the middle and zooming out on both sides
15. Using the text editing tool VIM
连接ftp服务器教程
How to create Apple Developer personal account P8 certificate
Getting started with webgl (3)
使用Scrapy框架爬取网页并保存到Mysql的实现
Keil5 does not support online simulation of STM32 F0 series
The rebound problem of using Scrollview in cocos Creator
[quick start of Digital IC Verification] 18. Basic grammar of SystemVerilog learning 5 (concurrent threads... Including practical exercises)
Pit avoidance: description of null values in in and not in SQL