itorator for of 的实现1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33class 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)
}
}
let container = new Container([1, 2, 3, 4, 5])
let iterator = container.getIterator()
while (iterator.hasNext()) {
console.log(iterator.next())
}