Created
April 26, 2014 03:42
-
-
Save KJlmfe/11311162 to your computer and use it in GitHub Desktop.
JavaScript 设计模式 - Iterator(迭代器模式) - 数组示例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 迭代器示例 */ | |
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