在 JavaScript 中实现迭代器模式

属于「行为型模式」,是「GoF」的 23 种设计模式之一。

提供按顺序遍历访问某个列表型数据结构的方法,使用者无需关心数据结构的实际情况。

实现

function Iterator(data) {
this.data = data;
this.current = 0;
}

Iterator.prototype.hasNext = function() {
return this.current < this.data.length - 1;
}

Iterator.prototype.getCurrent = function() {
return this.data[this.current];
}

Iterator.prototype.next = function() {
if (!this.hasNext()) {
return null;
}

this.current++;

return this.getCurrent();
}

Iterator.prototype.rewind = function() {
this.current = 0;
}

更多