Arrays have a built-in mapping function that acts like an iterator.
[1,2,3].map(function(input){console.log(input)});
Standard output:
1 2 3
In the worst case, you can easily design an iterator object, have not passed the full test, but if there are any errors, you can quickly get this work.
var Iterator = function(arr){ return { index : -1, hasNext : function(){ return this.index <= arr.length; }, hasPrevious: function(){ return this.index > 0; }, current: function(){ return arr[ this["index"] ]; }, next : function(){ if(this.hasNext()){ this.index = this.index + 1; return this.current(); } return false; }, previous : function(){ if(this.hasPrevious()){ this.index = this.index - 1 return this.current(); } return false; } } }; var iter = Iterator([1,2,3]); while(iter.hasNext()){ console.log(iter.next()); }
Dan
source share