迭代器模式概念:
迭代器模式提供一种方法顺序访问一个聚合对象中各个元素,而不需要暴露该方法中的内部表示
jquery中我们经常会用到的一个each函数就是迭代器模式。
迭代器模式的作用:
1.为了遍历不同的集合结构提供一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作。
2.对于集合内部结构常常变化各异,我们不想暴露其内部结构的话,但有不想让客户代码透明的访问其中的
元素,这种情况下我们可以使用迭代器模式
注意事项
1.一般的迭代,我们至少要有2个方法,hasNext()和next(),这样才能做到遍历所有对象
2.遍历的同事更改迭代器所有的集合结构可能会导致问题(比如c#的forEach里不允许修改item)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
var arr = ['test','2','3'];
var diedai = (
function(){
var length = arr.length;
index=0;
return {
hasNext:function(){
return index<length;
},
next:function(){
var data = arr[index];
index = index+1;
return data;
},
reset:function(){
index = 0;
}
}
}
)()
while(diedai.hasNext()){
console.log(diedai.next());
}
</script>
</body>
</html>
在jquery中的应用
$.each(arr.function (index,val) {
console.log(index);
console.log(val);
});
本文学习自常见设计模式视频