JavaScript表示“集合”的数据结构有:Array、Object、Map、Set。
1、是一种统一的处理所有不同的数据结构的遍历器。
2、Iterator的作用:
- 为各种数据结构,提供一个统一的、简便的访问接口
- 使得数据结构的成员能够按某种次序排列
- ES6 创造了一种新的遍历命令
for...of
循环,Iterator 接口主要供for...of
消费
3、Iterator遍历过程:
- 创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。
- 第一次调用指针对象的
next
方法,可以将指针指向数据结构的第一个成员。 - 第二次调用指针对象的
next
方法,指针就指向数据结构的第二个成员。 - 不断调用指针对象的
next
方法,直到它指向数据结构的结束位置。
4、Iterator每次调用next方法,返回数据结构的当前成员信息,即返回一个包含value和done属性的对象,其中,value
属性是当前成员的值,done
属性是一个布尔值,表示遍历是否结束。
//模拟next方法 var it = 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 是可以省略的
5、遍历器与所遍历的数据结构是分开的。
//无限运行的遍历器对象 var it = idMaker(); it.next().value // 0 it.next().value // 1 it.next().value // 2 // ... function idMaker() { var index = 0; return { next: function() { return {value: index++, done: false}; } }; }
6、遍历器对象的 return(),throw()
如果你自己写遍历器对象生成函数,那么next
方法是必须部署的,return
方法和throw
方法是否部署是可选的。
return
方法的使用场合是,如果for...of
循环提前退出(通常是因为出错,或者有break
语句),就会调用return
方法。如果一个对象在完成遍历前,需要清理或释放资源,就可以部署return
方法。
function readLinesSync(file) { return { [Symbol.iterator]() { return { next() { return { done: false }; }, return() { file.close(); return { done: true }; } }; }, }; } // 情况一
//输出文件的第一行以后,就会执行return
方法,关闭这个文件 for (let line of readLinesSync(fileName)) { console.log(line); break; } // 情况二
//在执行return
方法关闭文件之后,再抛出错误。 for (let line of readLinesSync(fileName)) { console.log(line); throw new Error(); }
注意,return
方法必须返回一个对象,这是 Generator 规格决定的。