1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-25 03:02:21 +00:00
es6tutorial/docs/iterator.md
2014-04-23 03:48:41 +08:00

52 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Iterator遍历器
遍历器Iterator是一种协议任何对象只要部署这个协议就可以完成遍历操作。在ES6中遍历操作特指for...of循环。
ES6的遍历器协议规定部署了next方法的对象就具备了遍历器功能。next方法必须返回一个包含value和done两个属性的对象。其中value属性是当前遍历位置的值done属性是一个布尔值表示遍历是否结束。
```javascript
function makeIterator(array){
var nextIndex = 0;
return {
next: function(){
return nextIndex < array.length ?
{value: array[nextIndex++], done: false} :
{value: undefined, done: true};
}
}
}
var it = makeIterator(['a', 'b']);
it.next().value // 'a'
it.next().value // 'b'
it.next().done // true
```
上面代码定义了一个makeIterator函数它的作用是返回一个遍历器对象用来遍历参数数组。请特别注意next返回值的构造。
下面是一个无限运行的遍历器例子。
```javascript
function idMaker(){
var index = 0;
return {
next: function(){
return {value: index++, done: false};
}
}
}
var it = idMaker();
it.next().value // '0'
it.next().value // '1'
it.next().value // '2'
// ...
```