1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-27 20:32:21 +00:00

update iterator

This commit is contained in:
ruanyf 2015-11-03 20:47:44 +08:00
parent 5f3f250332
commit 56cd64119d

View File

@ -455,10 +455,38 @@ for (let x of obj) {
## 遍历器对象的return()throw()
遍历器对象除了具有`next`方法,还可以具有`return`方法和`throw`方法。如果你自己写遍历器生成函数,那么`next`方法是必须部署的,`return`方法和`throw`方法是否部署是可选的。
遍历器对象除了具有`next`方法,还可以具有`return`方法和`throw`方法。如果你自己写遍历器对象生成函数,那么`next`方法是必须部署的,`return`方法和`throw`方法是否部署是可选的。
`return`方法的使用场合是,如果`for...of`循环提前退出(通常是因为出错,或者有`break`语句或`continue`语句),就会调用`return`方法。如果一个对象在完成遍历前,需要清理或释放资源,就可以部署`return`方法。
```javascript
function readLinesSync(file) {
return {
next() {
if (file.isAtEndOfFile()) {
file.close();
return { done: true };
}
},
return() {
file.close();
return { done: true };
},
};
}
```
上面代码中,函数`readLinesSync`接受一个文件对象作为参数,返回一个遍历器对象,其中除了`next`方法,还部署了`return`方法。下面,我们让文件的遍历提前返回,这样就会触发执行`return`方法。
```javascript
for (let line of readLinesSync(fileName)) {
console.log(x);
break;
}
```
注意,`return`方法必须返回一个对象这是Generator规格决定的。
`throw`方法主要是配合Generator函数使用一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
## for...of循环