迭代器模式

记录迭代器模式

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

var agg = (function() {
var index = 0,
data = [1,2,3,4,5],
length = data.length;
return {
next: function() {
var element;
if(!this.hasNext()) {
return null;
}
element = data[index];
index = index + 1;
return element;
},
hasNext: function() {
return index < length;
},
rewind: function() {
index = 0;
},
current: function() {
return data[index];
}
}
})();

while(agg.hasNext()) {
console.log(agg.next())
}