本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2021-12-15
迭代器模式(Iterator):在不暴露对象内部结构的同时,可以顺序地访问聚合对象内部的元素,为遍历不同数据结构的“数据集合”提供统一的接口,遍历访问数据中的项,而不关系项的数据结构。
class Iterator {
constructor(list) {
this.list = list;
this.index = 0
}
next() {
if (this.hasNext()) {
return this.list[this.index++]
}
return null
}
hasNext() {
if (this.index >= this.list.length) {
return false
}
return true
}
}
const iterator = new Iterator([1,2,3,4,5]);
while(iterator.hasNext()){
console.log(iterator.next());
}
// each 封装each以便能手动终止循环
function each(arr, cb) {
for(let i = 0, l = arr.length; i < l; i++) {
if (cb.call(arr[i], arr[i], i, arr) === false) {
break;
}
}
}
each([1, 2, 3, 4, 5], function (v, i, a) {
if (v > 3) {
return false; // 手动终止循环
}
console.log(v)
})
JavaScript中本就实现很多迭代器接口,比如for, for…in, for…of,以及ES6的Iterator。