Iterator mode
- Sequential access to a collection
- The user does not need to know the internal structure of the collection (encapsulation)
JS simplified version UML class diagram
class Iterator {
constructor(container) {
this.list = container.list
this.index = 0
}
next() {
if (this.hasNext()) {
return this.list[this.index++]
}
return null
}
hasNext() {
if (this.index >= this.list.length) {
return false
}
return true
}
}
class Container {
constructor(list) {
this.list = list
}
// 生成遍历器
getIterator() {
return new Iterator(this)
}
}
// test
let container = new Container([1, 2, 3, 4, 5, 6])
let iterator = contianer.getIterator()
while(iterator.hasNext()) {
console.log(iterator.next())
}
Scenes
jQuery each
// 写出一个方法遍历这三种对象
funciton each(data) {
let $data = $(data) // 生成迭代器
$data.each(function(key, p) {
console.log(key, p)
})
}
// test
each(arr)
each(nodeList)
each($p)
ES6 Iterator
Why does it exist?- In ES6 syntax, there are already many data types for ordered sets
- Array Map Set String TpyedArray arguments NodeList
- There needs to be a unified interface to traverse all data types.
Note: object is not an ordered collection, you can use Map instead
What is it?
- The above data types have [Symbol.iterator] attributes
- The attribute value is a function, and the execution of the function returns an iterator
- This iterator has a next method to iterate the child elements in sequence
- Run
Array.prototype[Symbol.iterator]
to test
function each(data) {
// 生成遍历器
let iterator = data[Symbol.iterator]()
let item = {
done: false}
while(!item.done) {
item = iterator.next()
if (!item.done) {
console.log(item.value)
}
}
}
// test
let arr = [1, 2, 3, 4]
let nodeList = document.getElementsByTagName('p')
let m = new Map()
m.set('a', 100)
m.set('b', 200)
each(arr)
each(nodeList)
each(m)
ES6 Iterator 与Generator
- The value of Iterator is not limited to the above types of traversal
- And the use of Generator function
- That is, as long as the returned data meets the requirements of the Iterator interface
- You can use Iterator syntax, which is the iterator mode
Design principle verification
- Separate the iterator object from the target object
- Iterators isolate the user from the target object
- Comply with the open and closed principle