JS红宝书-第七章-迭代器与生成器

本章总结了迭代器与生成器的内容

迭代器

迭代器模式描述了一个方案,让某些结构可以称为 iterable
具体实现而言,只需要将对象的Symbol.iterator赋为一个工厂函数,工厂函数返回一个含next()函数的结构,其返回值为

1
2
{done:true, value:"sth"}
{done:false, value:"sth"}

例子如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let TestIterator = function () {
this[Symbol.iterator] = () => {
let x = 0
return {
next() {
return x++?{done:true, value:1}:{done:false, value:2}
}
}
}
}
let x = new TestIterator()
for(let i of x) {
console.log(i)
}

可接受该语言特性的结构有:

  • for-of
  • 解构
  • 扩展操作服
  • 集合
  • 映射
  • Promise.all()
  • Promise.race()
  • yield*操作符

提前终止迭代器

会出现的场景 :

  • for-of中break continue return throw语句会引发
  • 解构操作未消费所有值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let TestIterator = function () {
this[Symbol.iterator] = () => {
let x = 0
let need = 90
return {
next() {
return (x++ < need) ? {done: false, value: x} : {done: true}
},
return() {
console.log("early stopped")
console.log(x)
return {done: true}
}
}
}
}
let x = new TestIterator()
for(let i of x) {
console.log(i)
break;
}

不是所有的迭代器都能够被关闭,例如:数组的迭代器

生成器

生成器据具有的能力

  • 在一个函数块内进行暂停
  • 在一个函数块内恢复代码执行
    生成器实现了iterable接口
1
2
3
4
5
function *generator() {}
let generator = function *(){}
let x = {
* function() {}
}

生成器函数会产生一个生成器对象,实现了Iterator接口,可以通过next控制继续。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function *testGenerator() {
yield 1
yield 2
yield 3
yield 4
return 5
}
for(i of testGenerator()) console.log(i)
/*
输出
1
2
3
4
*/

产生可迭代对象

可以使用yield *产生可迭代对象

1
2
3
4
5
6
7
8
9
function *test() {
yield * [1, 2, 3]
}
for(let i of test()) console.log(i)
/*
1
2
3
*/

JS红宝书-第七章-迭代器与生成器
https://tech.jasonczc.cn/2022/language/javascript/redbook/7-iterator-and-generator/
作者
CZY
发布于
2022年4月28日
许可协议