1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 18:32:22 +00:00

docs(iterator): edit return() #708

This commit is contained in:
ruanyf 2018-07-02 14:16:27 +08:00
parent 3c44084f4b
commit e85f4dd15a

View File

@ -475,7 +475,7 @@ for (let x of obj) {
遍历器对象除了具有`next`方法,还可以具有`return`方法和`throw`方法。如果你自己写遍历器对象生成函数,那么`next`方法是必须部署的,`return`方法和`throw`方法是否部署是可选的。
`return`方法的使用场合是,如果`for...of`循环提前退出(通常是因为出错,或者有`break`语句`continue`语句),就会调用`return`方法。如果一个对象在完成遍历前,需要清理或释放资源,就可以部署`return`方法。
`return`方法的使用场合是,如果`for...of`循环提前退出(通常是因为出错,或者有`break`语句),就会调用`return`方法。如果一个对象在完成遍历前,需要清理或释放资源,就可以部署`return`方法。
```javascript
function readLinesSync(file) {
@ -495,7 +495,7 @@ function readLinesSync(file) {
}
```
上面代码中,函数`readLinesSync`接受一个文件对象作为参数,返回一个遍历器对象,其中除了`next`方法,还部署了`return`方法。下面的种情况,都会触发执行`return`方法。
上面代码中,函数`readLinesSync`接受一个文件对象作为参数,返回一个遍历器对象,其中除了`next`方法,还部署了`return`方法。下面的种情况,都会触发执行`return`方法。
```javascript
// 情况一
@ -505,12 +505,6 @@ for (let line of readLinesSync(fileName)) {
}
// 情况二
for (let line of readLinesSync(fileName)) {
console.log(line);
continue;
}
// 情况三
for (let line of readLinesSync(fileName)) {
console.log(line);
throw new Error();