迭代器模式(Iterator):提供一種方法順序一個聚合對象中各個元素,而又不暴露該對象內(nèi)部表示。
迭代器的幾個特點(diǎn)是:
一般的迭代,我們至少要有 2 個方法,hasNext()和 Next(),這樣才做做到遍歷所有對象,我們先給出一個例子:
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 + 2;
return element;
},
hasNext: function () {
return index < length;
},
rewind: function () {
index = 0;
},
current: function () {
return data[index];
}
};
} ());
使用方法和平時 C# 里的方式是一樣的:
// 迭代的結(jié)果是:1,3,5
while (agg.hasNext()) {
console.log(agg.next());
}
當(dāng)然,你也可以通過額外的方法來重置數(shù)據(jù),然后再繼續(xù)其它操作:
// 重置
agg.rewind();
console.log(agg.current()); // 1
jQuery 里一個非常有名的迭代器就是 $.each 方法,通過 each 我們可以傳入額外的 function,然后來對所有的 item 項(xiàng)進(jìn)行迭代操作,例如:
$.each(['dudu', 'dudu', '酸奶小妹', '那個MM'], function (index, value) {
console.log(index + ': ' + value);
});
//或者
$('li').each(function (index) {
console.log(index + ': ' + $(this).text());
});
迭代器的使用場景是:對于集合內(nèi)部結(jié)果常常變化各異,我們不想暴露其內(nèi)部結(jié)構(gòu)的話,但又響讓客戶代碼透明底訪問其中的元素,這種情況下我們可以使用迭代器模式。