Iterator和Generator
前言:明白几个概念
迭代器:是帮助我们对某个数据结构进行遍历的对象。是一个具体的对象。
可迭代对象:
- 它和迭代器是不同的概念;
- 当一个对象实现了
iterable protocol
协议时,它就是一个可迭代对象; - 这个对象的要求是必须实现
@@iterator
方法,在代码中我们使用Symbol.iterator
访问该属性。
生成器是ES6中新增的一种函数控制、使用的方案,它可以让我们更加灵活的控制函数什么时候继续执行、暂停执行等。是一个函数。
1. 什么是可迭代对象和迭代器?
在JavaScript中,迭代器也是一个具体的对象,这个对象需要符合迭代器协议(iterator protocol):
- 迭代器协议定义了产生一系列值(无论是有限还是无限个)的标准方式;
- 那么在js中这个标准就是一个特定的
next
方法;
next
方法有如下的要求:
该对象包含 一个函数,该函数还返回一个具有两个属性的对象done
value
done(boolean)
-
- 如果迭代器可以产生序列中的下一个值,则为 false。(这等价于没有指定 done 这个属性。)
-
- 如果迭代器已将序列迭代完毕,则为 true。这种情况下,value 是可选的,如果它依然存在,即为迭代结束之后的默认返回值。
value
-
- 迭代器返回的任何
JavaScript
值。done
为true
时可省略。
- 迭代器返回的任何
function createArrayIterator(arr) {
let index = 0
return {
next: function() {
if (index < arr.length) {
return { done: false, value: arr[index++] }
} else {
return { done: true, value: undefined }
}
}
}
}
const names = ["abc", "cba", "nba"]
const nums = [10, 22, 33, 12]
const namesIterator = createArrayIterator(names)
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
const numsIterator = createArrayIterator(nums)
console.log(numsIterator.next())
console.log(numsIterator.next())
console.log(numsIterator.next())
console.log(numsIterator.next())
// 创建一个无限的迭代器
function createNumberIterator() {
let index = 0
return {
next: function() {
return { done: false, value: index++ }
}
}
}
const numberInterator = createNumberIterator()
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
console.log(numberInterator.next())
1.1 原生迭代器对象
平时创建的很多原生对象已经实现了可迭代协议,会生成一个迭代器对象的:
String
、Array
、Map
、Set
、arguments对象
、NodeList集合
1.2 可迭代对象的应用
- JavaScript中语法:
for ...of
、展开语法(spread syntax)
、yield*
、解构赋值(Destructuring_assignment)
. - 创建一些对象时:
new Map([Iterable])
、new WeakMap([iterable])
、new Set([iterable])
、new WeakSet([iterable])
. - 一些方法的调用:
Promise.all(iterable)
、Promise.race(iterable)
、Array.from(iterable)
.
1.3 迭代器的中断
迭代器在某些情况下会在没有完全迭代的情况下中断:
- 比如遍历的过程中通过
break
、continue
、return
、throw
中断了循环操作; - 比如在解构的时候,没有解构所有的值;
- 那么这个时候我们想要监听中断的话,可以添加
return
方法:
[Symbol.iterator]() {
let index = 0
return {
next: () => {
if (index < this.students.length) {
return { done: false, value: this.students[index++] }
} else {
return { done: true, value: undefined }
}
},
return: () => {
console.log("迭代器提前终止了~")
return { done: true, value: undefined }
}
}
}
2. 什么是生成器?
生成器是ES6中新增的一种函数控制、使用的方案,它可以让我们更加灵活的控制函数什么时候继续执行、暂停执行等。
平时我们会编写很多的函数,这些函数终止的条件通常是返回值或者发生了异常。
生成器函数也是一个函数,但是和普通的函数有一些区别:
- 首先,生成器函数需要在
function
的后面加一个符号:*
- 其次,生成器函数可以通过
yield关键字
来控制函数的执行流程: - 最后,生成器函数的返回值是一个Generator(生成器):生成器事实上是一种特殊的迭代器;
当遇到yield
时候值暂停函数的执行
当遇到return
时候生成器就停止执行
function* foo() {
console.log("函数开始执行~")
const value1 = 100
console.log("第一段代码:", value1)
yield value1
const value2 = 200
console.log("第二段代码:", value2)
yield value2
const value3 = 300
console.log("第三段代码:", value3)
yield value3
console.log("函数执行结束~")
return "123"
}
// generator本质上是一个特殊的iterator
const generator = foo()
console.log("返回值1:", generator.next())
console.log("返回值2:", generator.next())
console.log("返回值3:", generator.next())
console.log("返回值3:", generator.next())
输出:
函数开始执行~
第一段代码: 100
返回值1: { value: 100, done: false }
第二段代码: 200
返回值2: { value: 200, done: false }
第三段代码: 300
返回值3: { value: 300, done: false }
函数执行结束~
返回值3: { value: '123', done: true }
我们执行生成器函数foo并没有返回结果,它只是返回了一个生成器对象。
- 那么我们如何可以让它执行函数中的东西呢?调用
next
即可; - 我们之前学习迭代器时,知道迭代器的next是会有返回值的;
- 但是我们很多时候不希望
next
返回的是一个undefined
,这个时候我们可以通过yield
来返回结果;
2.1 生成器传递参数 – next
函数
函数既然可以暂停来分段执行,那么函数应该是可以传递参数的,我们是否可以给每个分段来传递参数呢?
答案是可以的;
- 我们在调用
next
函数的时候,可以给它传递参数,那么这个参数会作为上一个yield
语句的返回值。 - 注意:也就是说我们是为本次的函数代码块执行提供了一个值。
function* foo(num) {
console.log("函数开始执行~")
const value1 = 100 * num
console.log("第一段代码:", value1)
const n = yield value1
const value2 = 200 * n
console.log("第二段代码:", value2)
const count = yield value2
const value3 = 300 * count
console.log("第三段代码:", value3)
yield value3
console.log("函数执行结束~")
return "123"
}
// 生成器上的next方法可以传递参数
const generator = foo(5)
console.log(generator.next())
// 第二段代码, 第二次调用next的时候执行的
console.log(generator.next(10))
console.log(generator.next(25))
输出:
函数开始执行~
第一段代码: 500
{ value: 500, done: false }
第二段代码: 2000
{ value: 2000, done: false }
第三段代码: 7500
{ value: 7500, done: false }
2.2 生成器提前结束 – return
函数
return
传值后这个生成器函数就会结束,之后调用next
不会继续生成值了。
function* foo(num) {
console.log("函数开始执行~")
const value1 = 100 * num
console.log("第一段代码:", value1)
const n = yield value1
const value2 = 200 * n
console.log("第二段代码:", value2)
const count = yield value2
const value3 = 300 * count
console.log("第三段代码:", value3)
yield value3
console.log("函数执行结束~")
return "123"
}
const generator = foo(10)
console.log(generator.next())
// 第二段代码的执行, 使用了return
// 那么就意味着相当于在第一段代码的后面加上return, 就会提前终端生成器函数代码继续执行
// console.log(generator.return(15))
console.log(generator.return(generator.next(15)))
console.log(generator.next())
console.log(generator.next())
console.log(generator.next())
console.log(generator.next())
console.log(generator.next())
输出:
函数开始执行~
第一段代码: 1000
{ value: 1000, done: false }
第二段代码: 3000
{ value: { value: 3000, done: false }, done: true }
{ value: undefined, done: true }
{ value: undefined, done: true }
{ value: undefined, done: true }
{ value: undefined, done: true }
{ value: undefined, done: true }
2.3 生成器抛出异常 – throw
函数
除了给生成器函数内部传递参数之外,也可以给生成器函数内部抛出异常:
- 抛出异常后我们可以在生成器函数中捕获异常;
- 但是在
catch
语句中不能继续yield
新的值了,但是可以在catch
语句外使用yield
继续中断函数的执行。
function* foo() {
console.log("代码开始执行~")
const value1 = 100
try {
yield value1
} catch (error) {
console.log("捕获到异常情况:", error)
yield "abc"
}
console.log("第二段代码继续执行")
const value2 = 200
yield value2
console.log("代码执行结束~")
}
const generator = foo()
const result = generator.next()
generator.throw("error message")
console.log(generator.next())
输出:
代码开始执行~
捕获到异常情况: error message
第二段代码继续执行
{ value: 200, done: false }
3. 生成器替代迭代器
3.1 举例1:创建一个函数, 这个函数可以迭代一个范围内的数字。
- 迭代器写法:【注意
function
后没有*
】
function createRangeIterator(start, end) {
let index = start
return {
next: function () {
if (index < end) {
return { done: false, value: index++ }
} else {
return { done: true, value: undefined }
}
}
}
}
const rangeIterator = createRangeIterator(1, 5)
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
- 生成器写法:【注意
function
后有*
】
function* createRangeIterator(start, end) {
let index = start
while (index < end) {
yield index++
}
const rangeIterator = createRangeIterator(1, 5)
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
console.log(rangeIterator.next())
输出结果:
{ done: false, value: 1 }
{ done: false, value: 2 }
{ done: false, value: 3 }
{ done: false, value: 4 }
{ done: true, value: undefined }
{ done: true, value: undefined }
{ done: true, value: undefined }
3.2 举例2:使用生成器的三种写法
function* createArrayIterator(arr) {
// 3.第三种写法 yield*
// 这个时候相当于是一种yield的语法糖,只不过会依次迭代这个可迭代对象,每次迭代其中的一个值;
yield* arr
// // 2.第二种写法
// for (const item of arr) {
// yield item
// }
// 1.第一种写法
// yield "abc" // { done: false, value: "abc" }
// yield "cba" // { done: false, value: "abc" }
// yield "nba" // { done: false, value: "abc" }
}
const names = ["abc", "cba", "nba"]
const namesIterator = createArrayIterator(names)
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
3.3 举例3:自定义类迭代
// 3.class案例
class Classroom {
constructor(address, name, students) {
this.address = address
this.name = name
this.students = students
}
entry(newStudent) {
this.students.push(newStudent)
}
foo = () => {
console.log("foo function")
}
// [Symbol.iterator] = function*() {
// yield* this.students
// }
*[Symbol.iterator]() {
yield* this.students
}
}
const classroom = new Classroom("szu", "1102", ["abc", "cba", "nba"])
for (const item of classroom) {
console.log(item)
}
输出结果:
abc
cba
nba