当前位置:网站首页>Iterators and generators
Iterators and generators
2022-06-22 16:36:00 【xiao_ zhu_ ting_ feng】
1. iterator
iterator API Use next() Method traverses data in an iteratable object , Object etc. ,next() Method returns the iterator object IteratorResult Contains two properties : done and value.
let arr = ['foo'];
let iter = arr[Symbol.iterator]();
console.log(iter.next()); // { done: false, value: 'foo' }
console.log(iter.next()); // { done: true, value: undefined }
console.log(iter.next()); // { done: true, value: undefined }
console.log(iter.next()); // { done: true, value: undefined }To understand the principle , You can customize an iterator
// Define a class
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;
}
}
// Instantiate the class as an object
let counter = new Counter(3);
for (let i of counter) {
console.log(i);
}
// 1
// 2
// 32. generator ( Arrow functions cannot be used to define generator functions )
Generators are used to add elements to iterators , use yield Keyword to add an element to an iterator
generator
function *createIterator(items) {
for(i=0;i<items.length;i++){
yield items[i]
}
}
arr = [1,2,3]
it = createIterator(arr)
console.log(it.next())
console.log(it.next())
console.log(it.next())
边栏推荐
猜你喜欢
随机推荐
SAP web service cannot log in to SOA management page with soamanager
What is restful and what rules should be followed when designing rest APIs?
Test for API
nio使用可写事件处理一次性写不完情况
Pod type
Basic knowledge of audio and video | analysis of ANS noise suppression principle
Interview knowledge points
GD32F4xx MCU 驱动mcp2515扩展CAN接口
SAP ABAP 内部表:创建、读取、填充、复制和删除-06
首个赛博格人陨落背后:科技与渐冻症的极限赛跑
VHEDT业务发展框架
Make the text template in pycharm project support jinjia2 syntax
for..of vs. for..in 语句
二叉树练习第二弹
变量
Uniapp wechat applet obtains page QR code (with parameters)
迭代器与生成器
面试知识点
JS获取数据类型方法总结
Prometheus监控之Consul监控 [consul-exporter]







![[C language] deeply analyze the storage of integer and floating-point types in memory](/img/8b/12a4dc7a0c0e34e2add007592971dd.jpg)
