此地无银三百两

  • 首页

关于迭代器

发表于 2021-04-14

Iterator(遍历器)

遍历过程:

  1. 创建一个指针对象,指向当前数据结构的起始位置(遍历器对象本质上是一个只针对象)
  2. 第一次调用指针对象的next方法,将指针指向数据结构的第一个成员
  3. 第二次调用指针对象的next方法,指针指向数据结构的第二个成员
  4. 不断调用指针对象的next方法,直到它指向数据结构的 结束位置

模拟next()方法返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
varit=makeIterator(['a','b']);
it.next();//{value:"a",done:false}
it.next();//{value:"b",done:false}
it.next();//{value:undefined,done:true}
//遍历器生成函数
function makeIterator(array){
var nextIndex=0;
return {
next:function(){
return nextIndex<array.length?
{value:array[nextIndex++],done:false}:
{value:undefined,done:true};
}
};
}

对于遍历器对象来说,done:false和value:undefined属性是可以忽略的,因此以上makeIterator函数可以简写成以下形式

1
2
3
4
5
6
7
8
9
10
function makeIterator(array){
var nextIndex=0;
return {
next:function(){
return nextIndex<array.length?
{value:array[nextIndex++]}:
{done:true}
}
}
}

数据结构的默认Iterator接口

ES6规定,默认的Iterator接口部署在数据结构的Symbol.iterator属性,或者说一个数据结构只要具有了Symbol.iterator属性,就可以认为是可遍历的

1…242526…32

32 文章
11 标签
GitHub
© 2021 ajn404
由 Hexo 强力驱动
|
主题 — NexT.Pisces v5.1.4