File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change @@ -455,10 +455,38 @@ for (let x of obj) {
455
455
456
456
## 遍历器对象的return(),throw()
457
457
458
- 遍历器对象除了具有` next ` 方法,还可以具有` return ` 方法和` throw ` 方法。如果你自己写遍历器生成函数 ,那么` next ` 方法是必须部署的,` return ` 方法和` throw ` 方法是否部署是可选的。
458
+ 遍历器对象除了具有` next ` 方法,还可以具有` return ` 方法和` throw ` 方法。如果你自己写遍历器对象生成函数 ,那么` next ` 方法是必须部署的,` return ` 方法和` throw ` 方法是否部署是可选的。
459
459
460
460
` return ` 方法的使用场合是,如果` for...of ` 循环提前退出(通常是因为出错,或者有` break ` 语句或` continue ` 语句),就会调用` return ` 方法。如果一个对象在完成遍历前,需要清理或释放资源,就可以部署` return ` 方法。
461
461
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
+
462
490
` throw ` 方法主要是配合Generator函数使用,一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
463
491
464
492
## for...of循环
You can’t perform that action at this time.
0 commit comments