Skip to content

Commit 74bc512

Browse files
committed
docs(iterator): add iterator helpers
1 parent 7080152 commit 74bc512

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

docs/iterator.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -818,3 +818,43 @@ for (var n of fibonacci) {
818818
```
819819

820820
上面的例子,会输出斐波纳契数列小于等于 1000 的项。如果当前项大于 1000,就会使用`break`语句跳出`for...of`循环。
821+
822+
## 遍历器对象的工具方法
823+
824+
ES2025 为遍历器接口返回的遍历器对象,添加了一些工具方法,便于处理数据。
825+
826+
```javascript
827+
const arr = ['a', '', 'b', '', 'c', '', 'd', '', 'e'];
828+
829+
arr.values() // creates an iterator
830+
.filter(x => x.length > 0)
831+
.drop(1)
832+
.take(3)
833+
.map(x => `=${x}=`)
834+
.toArray()
835+
// ['=b=', '=c=', '=d=']
836+
```
837+
838+
上面示例中,arr 是一个数组,它的 values() 方法返回的是一个遍历器对象,以前要使用 for...of 循环来处理,现在有了工具方法,就可以直接链式处理了。
839+
840+
遍历器对象的工具方法,基本上与数组方法是对应的。
841+
842+
- 返回遍历器对象的方法
843+
- iterator.filter(filterFn)
844+
- iterator.map(mapFn)
845+
- iterator.flatMap(mapFn)
846+
- 返回布尔值的方法
847+
- iterator.some(fn)
848+
- iterator.every(fn)
849+
- 返回其他值的方法
850+
- iterator.find(fn)
851+
- iterator.reduce(reducer, initialValue?)
852+
- 不返回值的方法
853+
- iterator.forEach(fn)
854+
855+
以下是遍历器对象独有的方法。
856+
857+
- iterator.drop(limit):返回一个遍历器对象,丢弃前 limit 个成员。
858+
- iterator.take(limit):返回一个遍历器对象,包含前 limit 个成员。
859+
- iterator.toArray():返回一个数组,包含所有成员。
860+

0 commit comments

Comments
 (0)