数组的迭代器
2016-02-24
147
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]);
我想通过添加动态值来重写此功能
added : function(data){
arr.push(data);
this.index++
}
iter.added(1);
iter.added(6);
iter.added(7);
iter.added(8);
怎么做? 我知道 ES 6 中的迭代器 https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Iterator 但我希望支持 IE
1个回答
您需要添加与您发布的内容类似的
added()
函数,然后更新 index 的初始值,以便 next() 和 previous() 函数正常工作。您需要将其设置为输入数组长度,以便 next() 函数知道您位于最后一个元素。
var Iterator = function(arr){ return {
index : arr.length,
hasNext : function(){ return this.index < arr.length - 1; },
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;
},
added: function(x){
arr.push(x);
this.index++;
}
}
};
var iter = Iterator([1,2,3]);
console.log(iter)
iter.added(1);
iter.added(6);
iter.added(7);
iter.added(8);
console.log(iter)
console.log(iter.next())
console.log(iter.previous())
console.log(iter.previous())
console.log(iter.previous())
console.log(iter.previous())
console.log(iter.next())
console.log(iter.current())
输出:
Object {arr: Array[3], index: 3}
Object {arr: Array[7], index: 7}
false
8
7
6
1
6
6
这是小提琴: https://jsfiddle.net/8ojcrnkn/5/
希望有所帮助!
ak_
2016-02-24