gpt4 book ai didi

javascript - 数组的迭代器

转载 作者:行者123 更新时间:2023-11-27 23:18:33 27 4
gpt4 key购买 nike

来自JavaScript Iterators

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

最佳答案

您需要添加类似于您发布的内容的 added() 函数,然后更新索引的初始值,以便 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

这是在 fiddle 中:https://jsfiddle.net/8ojcrnkn/5/

希望有帮助!

关于javascript - 数组的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35604787/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com