Iterator 的构造函数直接接收 list,这样的话就不需要 Container 类了。
class Iterator {
constructor (list) {
this.list = list
this.index = 0
}
next () {
if (this.hasNext()) {
return this.list[this.index++]
}
}
hasNext () {
if (this.index >= this.list.length) {
return false
}
return true
}
}
let list = [1, 2, 3, 4, 5, 6]
let iterator = new Iterator(list)
while (iterator.hasNext()) {
console.log(iterator.next())
}