Skip to content

Commit 56cd641

Browse files
committed
update iterator
1 parent 5f3f250 commit 56cd641

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

docs/iterator.md

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -455,10 +455,38 @@ for (let x of obj) {
455455

456456
## 遍历器对象的return(),throw()
457457

458-
遍历器对象除了具有`next`方法,还可以具有`return`方法和`throw`方法。如果你自己写遍历器生成函数,那么`next`方法是必须部署的,`return`方法和`throw`方法是否部署是可选的。
458+
遍历器对象除了具有`next`方法,还可以具有`return`方法和`throw`方法。如果你自己写遍历器对象生成函数,那么`next`方法是必须部署的,`return`方法和`throw`方法是否部署是可选的。
459459

460460
`return`方法的使用场合是,如果`for...of`循环提前退出(通常是因为出错,或者有`break`语句或`continue`语句),就会调用`return`方法。如果一个对象在完成遍历前,需要清理或释放资源,就可以部署`return`方法。
461461

462+
```javascript
463+
function readLinesSync(file) {
464+
return {
465+
next() {
466+
if (file.isAtEndOfFile()) {
467+
file.close();
468+
return { done: true };
469+
}
470+
},
471+
return() {
472+
file.close();
473+
return { done: true };
474+
},
475+
};
476+
}
477+
```
478+
479+
上面代码中,函数`readLinesSync`接受一个文件对象作为参数,返回一个遍历器对象,其中除了`next`方法,还部署了`return`方法。下面,我们让文件的遍历提前返回,这样就会触发执行`return`方法。
480+
481+
```javascript
482+
for (let line of readLinesSync(fileName)) {
483+
console.log(x);
484+
break;
485+
}
486+
```
487+
488+
注意,`return`方法必须返回一个对象,这是Generator规格决定的。
489+
462490
`throw`方法主要是配合Generator函数使用,一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
463491

464492
## for...of循环

0 commit comments

Comments
 (0)