![](https://box.kancloud.cn/b7aaeba7392492e519808a3e47f39477_614x229.png)
~~~
class Iterator {
constructor(conatiner) {
this.list = conatiner.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())
}
~~~
![](https://box.kancloud.cn/e3f794695296a50edbb6dc8ebc67c298_538x339.png)
![](https://box.kancloud.cn/51b93505e23982722df042d283663387_462x162.png)
![](https://box.kancloud.cn/5c0085536a28225c525ab79d7e5cfce1_291x68.png)
![](https://img.kancloud.cn/ed/2d/ed2d6a927718b6129a4d66abc114d468_546x363.png)