当前位置:网站首页>Iterator of JS
Iterator of JS
2022-06-30 04:10:00 【Runqing】
Application of iterators
Data processing : Summarize the numbers in the following objects
let a = {
b: {
c: [
'1',
'2',
'3'
],
d: [
'4',
'5',
'6',
'7'
],
e: [
'8',
'9',
'10'
]
}
}
// Not available here for...of, Is due to Object Of prototype Not on [Symbol.iterator] Method , Therefore, complains
for (let o of a) {
console.log(o)
}
// Uncaught TypeError: authors is not iterable
If you want to traverse the object , First, the data format can be changed
for (let key in a) {
let r = []
for (let k in a[key]) {
r = r.concat(a[key][k])
}
console.log(r)
}
// ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
Second, through customization Iterator Interface , Make it traversable
a[Symbol.iterator] = function () {
let b = this.b
let keys = Reflect.ownKeys(b)
let values = []
return {
next () {
if (!values.length) {
if (keys.length) {
values = b[keys[0]]
keys.shift()
}
}
return {
done: !values.length,
value: values.shift()
}
}
}
}
// Defined [Symbol.iterator] After the interface , Can be for...of Iterative
for (let o of a) {
console.log(o)
}
Iterative protocol
If you make an object traversable , We must abide by the iterative protocol , Requirements of the agreement
1. Object to deploy a Symbol.iterator by key Key
2. Symbol.iterator The value of is a parameterless function that complies with the iterator protocol
iterator protocol
The iterator protocol requires the following conditions :
1. An object must contain a parameterless function next
2.next The return value is also an object , contain done and value attribute . among done Indicates whether the traversal ends ,value Returns the value of the current traversal .
With default Iterator The data type of the interface
ES6 Some data structures of Iterator Interface ( For example, array ), I.e. no handling , Can be for…of Loop traversal . The reason lies in , These data structures are deployed natively Symbol.iterator attribute :
Array
Map
Set
String
TypedArray
Functional arguments object
NodeList object
Generator and Iterator
Generator Naturally, it satisfies the iterative protocol , utilize Generator There is no need to show the write iteration protocol ( because Generator contain next Methods and contains done、value Property ).
// use generator Rewrite the iterator interface function above :
a[Symbol.iterator] = function * () {
let b = this.b
let keys = Reflect.ownKeys(b)
let values = []
while (1) {
if (!values.length) {
if (keys.length) {
values = b[keys[0]]
keys.shift()
yield values.shift()
} else {
return false
}
} else {
yield values.shift()
}
}
}
边栏推荐
- Pytorch Profiler+ Tensorboard + VS Code
- Jour 9 Gestion des scripts et des ressources
- El upload upload file (manual upload, automatic upload, upload progress)
- 华为云原生——数据开发与DataFactory
- lego_loam 代码阅读与总结
- Educoder group purchase suspension box page production
- About manipulator on Intelligent Vision Group
- Knowledge - how to build rapport in sales with 3 simple skills
- When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
- RPC correction
猜你喜欢

Smart use of bitmap to achieve 100 million level massive data statistics

(04). Net Maui actual MVVM

第十天 数据的保存与加载

Share an example of a simple MapReduce method using a virtual machine

如何通过进程启动来分析和解决EasyCVR内核端口报错问题?

The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure

NER中BiLSTM-CRF解读score_sentence

El upload upload file (manual upload, automatic upload, upload progress)

Simple theoretical derivation of SVM (notes)

When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
随机推荐
Daily summary of code knowledge
【论文阅读|深读】Role2Vec:Role-Based Graph Embeddings
Slam mapping, automatic navigation and obstacle avoidance based on ROS (bingda robot)
A solution to the problem of "couldn't open file /mnt/repodata/repomd.xml"
Integrating viewbinding and viewholder with reflection
dotnet-exec 0.5.0 released
Use ideal to connect to the database. The results show some warnings. How to deal with this part
.NET 7 的 JWT 配置太方便了!
[operation] write CSV to database on May 28, 2022
Hebb and delta learning rules
接口测试--如何分析一个接口?
Day 9 script and resource management
How to solve the problem of link hyperlinks when trying to link the database?
lego_loam 代码阅读与总结
Cloud native -- websocket of Web real-time communication technology
(Reprinted) an article will take you to understand the reproducing kernel Hilbert space (RKHS) and various spaces
【图像融合】基于交叉双边滤波器和加权平均实现多焦点和多光谱图像融合附matlab代码
使用IDEAL连接数据库,运行出来了 结果显示一些警告,这部分怎么处理
[Thesis reading | deep reading] role2vec:role based graph embeddings
技术分享| 融合调度中的广播功能设计