iterator

时间:2020-01-09 21:02:11   收藏:0   阅读:78

JavaScript原有的表示“集合”的数据结构,主要是数组(Array)和对象(Object),ES6又添加了Map和Set。这样就有了四种数据集合,用户还可以组合使用它们,定义自己的数据结构,比如数组的成员是Map,Map的成员是对象。

这样就需要一种统一的接口机制,来处理所有不同的数据结构。

遍历器(Iterator)是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。

1.数组集合

1 {
2     let arr=[‘hello‘,‘world‘];
3     let map = arr[Symbol.iterator]();
4     console.log(map.next())
5     console.log(map.next())
6     console.log(map.next())
7 }

2.给对象实现iterator接口,使其能用for of

 1 {
 2     let obj = {
 3         start:[1,2,3],
 4         end:[4,5,6],
 5         [Symbol.iterator](){
 6             let self = this ;
 7             let index = 0 ;
 8             let arr = self.start.concat(self.end);
 9             let len = arr.length;
10             return{
11                 next(){
12                     if(index < len){
13                         return{
14                             value:arr[index++],
15                             done:false
16                         }
17                     }else{
18                         return{
19                             value:arr[index++],
20                             done:true
21                         }
22                     }
23                 }
24             }
25         }
26     }
27     for(let key of obj){
28         console.log(key)   //1 2 3 4 5 6
29     }
30 }
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!