Skip to content

Instantly share code, notes, and snippets.

@KJlmfe
Created April 26, 2014 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KJlmfe/11311162 to your computer and use it in GitHub Desktop.
Save KJlmfe/11311162 to your computer and use it in GitHub Desktop.
JavaScript 设计模式 - Iterator(迭代器模式) - 数组示例
/* 迭代器示例 */
var agg = (function() {
var index = 0,
data = [1,2,3,4,5,6];
length = data.length;
var api = {
next: function() {
if(!this.hasNext()) {
return null;
}
return data[index++];
},
hasNext: function() {
return index < length;
},
rewind: function() {
index = 0;
},
current: function() {
return data[index];
}
};
return api;
})();
//测试
while(agg.hasNext()) {
console.log(agg.next());
}
agg.rewind();
console.log(agg.current());
//输出
//1
//2
//3
//4
//5
//6
//1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment