
说明
1、提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示
2、可分为:内部迭代器和外部迭代器
内部迭代器: 内部已经定义好迭代规则,外部只需要调用一次即可。
外部迭代器:必须显示的请求迭代下一个元素。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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());
}
|
以上就是 js迭代器模式的介绍,希望对大家有所帮助。更多js学习指路:js教程
推荐操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。