js迭代器模式是什么
小妮浅浅
2021-08-20 09:24:563614浏览 · 0收藏 · 0评论

说明
1、提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示
2、可分为:内部迭代器和外部迭代器
内部迭代器: 内部已经定义好迭代规则,外部只需要调用一次即可。
外部迭代器:必须显示的请求迭代下一个元素。
实例
// 迭代器
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 arr = [1, 2, 3, 4, 5, 6];
const ite = new Iterator();
while(ite.hasNext()) {
console.log(ite.next()); // 依次打印 1 2 3 4 5 6
}以上就是 js迭代器模式的介绍,希望对大家有所帮助。更多js学习指路:js教程
推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。
关注公众号,随时随地在线学习