当前位置:网站首页>Iterators and generators in JS (detailed explanation)
Iterators and generators in JS (detailed explanation)
2022-07-23 07:05:00 【m0_ sixty-three million eight hundred and thirty-one thousand n】
Catalog
2. Basic applications of iterators
4. application : Custom traversal data
2. Basic application of generator
4. application : Analog data acquisition
One , iterator
1. The concept of iterators
iterator (lterator) It's an interface , Provide unified access mechanism for different data structures .
Any data structure only needs to be deployed lterator Interface , You can complete the traversal operation .
// The following data structures support lterator Interface
String
Array
Map
Set
TypedArray
Function arguments object
NodeList object 2. Basic applications of iterators
for/of loop , Extension operators You can directly manipulate iteratable objects
const xiyou = [' iterator ',' generator '];
for (let v of xiyou) {
console.log(v) // iterator , generator
}
// Be careful :
// for/of v Values store key values
// for/in v The value saves the key name
data = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(Math.max(...data)); // 8Iterators can also be used for structure assignment
let arr = [ 10 , 18 , 20];
let [a , b , c] = arr;
console.log(c); // 203. Principle of iterator
First of all, understand 3 There are two different types
- Iteratable object : Be similar to Array,Set,Map Can be iterated .
- Iterator object : Means any having next() Methodical , And the method returns the object of the iteration result object , Used to perform iterations .
- Iterator result object : It refers to having attributes value and done The object of , Used to save the results of each iteration .
To iterate over an iteratable object , First call the iterator method to get an iteration object , Then call the iterator object repeatedly next() Method , Until the iterator result object is returned done The attribute is true;
The iterator method of an iteratable object is named :[Symbol.iterator]
4. application : Custom traversal data
Custom traversal data , Think of iterators
const obj = {
name: 'yiban',
friend: [
'duan',
'zhou',
'zhang',
'wei'
],
[Symbol.iterator]() {
// Index variables
let index = 0;
// Create a pointer object
return {
// establish next Method ( must )
next: () => { // Here the arrow function solves this Point to the problem
if (index < this.friend.length) {
const res = {
value: this.friend[index],
done: false
};
index++;
return res
} else {
return {
value: undefined,
done: true
}
}
}
}
}
}
for (let v of obj) {
console.log(v)
}Two , generator
1. Generator concept
generator (Generators) It's a powerful new ES6 Syntax defined iterator , Is an asynchronous programming solution .
A generator is a special function .
2. Basic application of generator
When calling the generator next() When the method is used , The generator function will run until the first yield In terms of expression , When running for the second time, it will stop at the second yield On .
// Calling the generator function below will not run the following code , Instead, it returns a generator object
// Calling the next() Method will run
function* fn() {
console.log(' First execution ');
yield ' Split line 1'; //yield The split line calls the position where the split is performed only once at a time
console.log(' Second execution ');
yield ' Split line 2';
console.log(' Third execution ');
yield ' Split line 3';
console.log(' The fourth execution ');
}
// Call the generator function , Get a generator
let han = fn();
console.log(han.next()); // First execution {value: ' Split line 1', done: false}
console.log(han.next()); // Second execution {value: ' Split line 2', done: false}
console.log(han.next()); // Third execution {value: ' Split line 3', done: false}
console.log(han.next()); // The fourth execution {value: undefined, done: true}
3.yield Value of expression
Generator passes yield Returns a value to the caller , The caller passes through next() Method to pass values to the generator .
When calling the generator next() When the method is used , Run to the first yield expression ,yield The expression after the keyword will be evaluated , This value becomes next() Return value of the call , At this time, the generator function is evaluating yield The expression stops on the way , Next call next() When the method is used , The parameters passed in will become suspended yield Value of expression .
function* fn(str) {
console.log(str); // The ginseng
let a = yield 1; //a == 'b'
console.log(a); // b
let b = yield 2; //b == 'c'
console.log(b); // c
let c = yield 3; //c == 'd'
console.log(c); // d
return 100
}
// Execute get iterator object
let han = fn(' The ginseng ');
//han.next() Method can pass in arguments
console.log(han.next('a')); // First call ; Parameters will be discarded , Generator echo 1
// The return value of the passed in parameter is the first yiele Overall return result
console.log(han.next('b')); // Parameter is b, Generator echo 2
console.log(han.next('c')); // Parameter is c, Generator echo 3
console.log(han.next('d')); // Parameter is d, Generator echo 1004. application : Analog data acquisition
Simulation acquisition User data Order data Commodity data
1 Print user data in seconds ,1 Print the order data in seconds ,1 Print the product data in seconds
function fa() {
setTimeout(() => {
let yon = ' User data ';
// Pass in parameters and call
han.next(yon);
}, 1000);
}
function fb() {
setTimeout(() => {
let din = ' Order data ';
han.next(din);
}, 1000);
}
function fc() {
setTimeout(() => {
let shang = ' Commodity data ';
han.next(shang);
}, 1000);
}
function* fn() {
let a = yield fa();
console.log(a); //1s User data
let b = yield fb();
console.log(b); //2s Order data
let c = yield fc();
console.log(c); //3s Commodity data
}
let han = fn();
// call
han.next();3、 ... and , summary
Generator is a powerful general control structure , You can use the generator in a single thread js Create some kind of collaborative threading system in the code . Although these functions are asynchronous , But the code seems to be synchronized in sequence .
Using generators to do asynchronous operations will make the code difficult to interpret ,ES6+ Added async/await and promise Provides asynchronous programming solutions .
边栏推荐
- 100 行代码透彻解析 RPC 原理
- Web3产品经理指南:如何面向加密世界
- Livegbs camera web page low delay plug-in free live broadcast implementation
- Jupyternotebook runs to the specified line
- 第五章 传播训练
- How to embed the monitoring image into wechat official account for live broadcast
- 记事本文件太大打不开怎么办?TXT文件太大无法打开现象的解决办法介绍
- STL container -string Simulation Implementation
- 第八章 使用时序数据
- PHP 防止或检测页面被刷新 post重复提交问题
猜你喜欢
随机推荐
LiveGBS-摄像机网页低延时无插件直播实现
苹果开发者账号怎么免费注册申请以便第一时间享受升级体验
科学计算与仿真-高斯牛顿法的非线性最小二乘问题简单介绍与应用
上交所行情文件解析之mktdt03
龙芯掌门人吐苦水:我们有世界第一性能的CPU,但可惜没人用!
Livegbs camera web page low delay plug-in free live broadcast implementation
100 lines of code thoroughly analyze RPC principle
js中的迭代器与生成器(详解)
电脑桌面卡住了怎么办?电脑死机桌面卡死现象的解决办法介绍
Installation and login installation
ABAP ALV steps
第零章 Encog入门介绍
个性自定义财付通姓名 自定义财付通为马化腾等任意名字图解
《STL仿函数》priority_queue模拟实现
MyCms 自媒体商城 v3.5 发布,新增免费插件
abap ALV总结整理
Jupyternotebook运行到指定行
What problems do let and const solve and the differences between them
Pikachu shooting range SQL injection search injection clearance steps
在 MySQL 中使用枚举的陷阱一定要注意!









