目录
1_迭代器介绍
迭代器(iterator),使用户在容器对象(container,例如链表或数组)上遍访的对象,使用该接口无需关心对象的内部实现细节。
- 其行为像数据库中的光标,迭代器最早出现在1974年设计的CLU编程语言中;
- 在各种编程语言的实现中,迭代器的实现方式各不相同,但是基本都有迭代器,比如Java、Python等;
迭代器是帮助对某个数据结构进行遍历的对象。
在JavaScript中,迭代器也是一个具体的对象,这个对象需要符合迭代器协议(iterator protocol):
- 迭代器协议定义了产生一系列值(无论是有限还是无限个)的标准方式;
- 在JavaScript中这个标准就是一个特定的next方法;
next
方法有如下的要求:
-
一个无参数或者一个参数的函数,返回一个应当拥有以下两个属性的对象:
-
done(boolean)
- 如果迭代器可以产生序列中的下一个值,则为 false。(没有迭代完毕)
- 如果迭代器已将序列迭代完毕,则为 true。这种情况下,value 是可选的,如果它依然存在,即为迭代结束之后的默认返回值。
-
value:迭代器返回的任何 JavaScript 值。done 为 true 时可省略
const names = ["abc", "cba", "nba"]
//第一个版本的迭代器
// 给数组names创建一个迭代器(迭代器: names的跌大气)
let index = 0
const namesIterator = {
next: function() {
// done: Boolean
// value: 具体值/undefined
if (index < names.length) {
return { done: false, value: names[index++] }
} else {
return { done: true }
}
}
}
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
const names = ["abc", "cba", "nba"]
//第二个版本
// 封装一个函数 创建数组通用的迭代器
function createArrayIterator(arr) {
let index = 0
return {
next: function() {
if (index < arr.length) {
return { done: false, value: arr[index++] }
} else {
return { done: true }
}
}
}
}
const namesIterator = createArrayIterator(names)
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
console.log(namesIterator.next())
2_可迭代对象
上面的代码整体来说看起来是有点奇怪的:
- 获取一个数组的时候,需要自己创建一个index变量,再创建一个所谓的迭代器对象;
- 事实上可以对上面的代码进行进一步的封装,让其变成一个可迭代对象;
可迭代对象?
- 它和迭代器是不同的概念;
- 当一个对象实现了iterable protocol协议时,它就是一个可迭代对象;
- 这个对象的要求是必须实现 @@iterator 方法,在代码中使用
Symbol.iterator
访问该属性;
转成可迭代对象的好处?
- 当一个对象变成一个可迭代对象的时候,就可以进行某些迭代操作;
- 比如
for...of
操作时,其实就会调用它的 @@iterator 方法;
遍历数组
// 将infos变成一个可迭代对象
/*
1.必须实现一个特定的函数: [Symbol.iterator]
2.这个函数需要返回一个迭代器(这个迭代器用于迭代当前的对象)
*/
const infos = {
friends: ["kobe", "james", "curry"],
[Symbol.iterator]: function() {
let index = 0
const infosIterator = {
next: function() {
// done: Boolean
// value: 具体值/undefined
if (index < infos.friends.length) {
return { done: false, value: infos.friends[index++] }
} else {
return { done: true }
}
}
}
return infosIterator
}
}
// 可迭对象可以进行for of操作
for (const item of infos) {
console.log(item) //换行打印数组的每一个元素
}
遍历对象
const infos = {
name: "hhh",
age: 18,
height: 1.88,
[Symbol.iterator]: function() {
const entries = Object.entries(this)//entries() 方法返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)
let index = 0
const iterator = {
next: function() {
if (index < entries.length) {
return { done: false, value: entries[index++] }
} else {
return { done: true }
}
}
}
return iterator
}
}
//【遍历对象】 可迭对象可以进行for of操作
for (const item of infos) {
const [key, value] = item
console.log(key, value)
}
3_原生迭代器对象
平时创建的很多原生对象已经实现了可迭代协议,会生成一个迭代器对象: String、Array、Map、Set、arguments对象、NodeList集合
// 1.数组
const names = ["abc", "cba", "nba"]
for (const name of names) {
console.log(name)
}
console.log(names[Symbol.iterator]())
// 2.Set
const set = new Set(["abc", "cba", "nba"])
for (const item of set) {
console.log(item)
}
const setIterator = set[Symbol.iterator]()
console.log(setIterator.next())
console.log(setIterator.next())
console.log(setIterator.next())
// 3.arguments
function foo() {
for (const arg of arguments) {
console.log(arg)
}
}
foo(123, 321, 111, 222)
可迭代对象的应用
- 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);
demo
// 1.用在特定的语法上
const names = ["abc", "cba", "nba"]
const info = {
name: "hhh",
age: 18,
height: 1.88,
[Symbol.iterator]: function() {
const values = Object.values(this)
let index = 0
const iterator = {
next: function() {
if (index < values.length) {
return { done: false, value: values[index++] }
} else {
return { done: true }
}
}
}
return iterator
}
}
function foo(arg1, arg2, arg3) {
console.log(arg1, arg2, arg3)
}
foo(...info) //hhh 18 1.88
// 2.一些类的构造方法中, 也是传入的可迭代对象
const set = new Set(["aaa", "bbb", "ccc"])
const set2 = new Set("abc")
console.log(set2) //Set(3) {'a', 'b', 'c'}
const set3 = new Set(info)
console.log(set3) //Set(3) {'hhh', 18, 1.88}
// 3.一些常用的方法
const p1 = Promise.resolve("aaaa")
const p2 = Promise.resolve("aaaa")
const p3 = Promise.resolve("aaaa")
const pSet = new Set()
pSet.add(p1)
pSet.add(p2)
pSet.add(p3)
Promise.all(pSet).then(res => {
console.log("res:", res) //res: (3) ['aaaa', 'aaaa', 'aaaa']
})
function bar() {
// console.log(arguments)
// 将arguments转成Array类型
const arr = Array.from(arguments)
console.log(arr)
}
bar(111, 222, 333) //(3) [111, 222, 333]
4_自定义类的迭代
//自定义类
class Person {
// 构造类方法
constructor(name, age, height, friends) {
this.name = name
this.age = age
this.height = height
this.friends = friends
}
// 实例方法
running() {}
// 可迭代对象friends
[Symbol.iterator]() {
let index = 0
const iterator = {
next: () => {
if (index < this.friends.length) {
return { done: false, value: this.friends[index++] }
} else {
return { done: true }
}
}
}
return iterator
}
}
//构造类的实例对象
const p1 = new Person("hhh", 18, 1.88, ["curry", "kobe", "james", "tatumu"])
const p2 = new Person("kobe", 30, 1.98, ["curry", "james", "aonier", "weide"])
//遍历类
for (const item of p2) {
console.log(item) //curry james aonier weide
}
迭代器的中断
迭代器在某些情况下会在没有完全迭代的情况下中断:
- 比如遍历的过程中通过break、return、throw中断了循环操作;
- 比如在解构的时候,没有解构所有的值;
如果要监听中断的话,可以添加return方法。
demo
//自定义类
class Person {
// 构造类方法
constructor(name, age, height, friends) {
this.name = name
this.age = age
this.height = height
this.friends = friends
}
// 实例方法
running() {}
// 可迭代对象friends
[Symbol.iterator]() {
let index = 0
const iterator = {
next: () => { //迭代
if (index < this.friends.length) {
return { done: false, value: this.friends[index++] }
} else {
return { done: true }
}
},
return: () => { //中断
console.log("监听到迭代器中断了")
return { done: true }
}
}
return iterator
}
}
//构造类的实例对象
const p1 = new Person("hhh", 18, 1.88, ["curry", "kobe", "james", "tatumu"])
// 遍历类 +监听中断
for (const item of p1) {
console.log(item)
if (item === "james") {
break
}
}
5_生成器
生成器是ES6中新增的一种函数控制、使用的方案,它可以更加灵活的控制函数什么时候继续执行、暂停执行等。 平时编写的函数,终止的条件通常是返回值或者发生了异常。
生成器函数也是一个函数,但是和普通的函数有区别:
-
首先,生成器函数需要在
function
的后面加一个符号:*
-
其次,生成器函数可以通过
yield
关键字来控制函数的执行流程: -
最后,生成器函数的返回值是一个
Generator
(生成器): -
生成器事实上是一种特殊的迭代器;
-
MDN:Instead, they return a special type of iterator, called a Generator.
5.1_生成器函数执行
下面的生成器函数foo的执行体压根没有执行,它只是返回了一个生成器对象。
- 让它执行函数中的东西,调用next即可;
- 已知迭代器的
next
是会有返回值的; - 有时不希望next返回的是一个undefined,可以通过
yield
来返回结果
/*
生成器函数:
1.function后面会跟上符号: *
2.代码的执行可以被yield控制
3.生成器函数默认在执行时, 返回一个生成器对象
* 要想执行函数内部的代码, 需要生成器对象, 调用它的next操作
* 当遇到yield时, 就会中断执行
*/
// 1.定义了一个生成器函数
function* foo() {
console.log("1111")
console.log("2222")
yield
console.log("3333")
console.log("4444")
yield
console.log("5555")
console.log("6666")
}
// 2.调用生成器函数, 返回一个 生成器对象
const generator = foo() //返回生成器
// 调用next方法
generator.next() //执行到第一个yield,就暂停执行
//1111
//2222
generator.next() //执行到第二个yield,就暂停执行
//3333
//4444
generator.next() //执行剩余的代码
//5555
//6666
5.2_生成器传递参数 – next函数
函数可以暂停来分段执行,那么函数也可以给每个分段来传递参数
- 在调用next函数的时候,给它传递参数,那么这个参数会作为上一个yield语句的返回值;
- 注意:也就是说是为本次的函数代码块执行提供了一个值;
- 不希望next返回的是一个undefined,可以通过
yield
来返回结果
// 1.定义了一个生成器函数
function* foo(name1) {
console.log("执行内部代码:1111", name1)
const name2 = yield "aaaa"
console.log("执行内部代码:3333", name2)
const name3 = yield "bbbb"
console.log("执行内部代码:5555", name3)
yield "cccc"
return undefined
}
// 2.调用生成器函数, 返回一个 生成器对象
const generator = foo("next1")
// 调用next方法 ,返回的是生成器的值
// console.log(generator.next()) // { done: false, value: "aaaa" }
// console.log(generator.next()) // { done: false, value: "bbbb" }
// console.log(generator.next()) // { done: false, value: "cccc" }
// console.log(generator.next()) // {done: true, value: undefined}
// 4.给函数每次执行的时候, 传入参数
console.log(generator.next())
// 执行内部代码:1111 next1 【yield控制执行的代码】
// {value: 'aaaa', done: false} 【生成器的返回值】
console.log(generator.next("next2"))
//执行内部代码:3333 next2
//{value: 'bbbb', done: false}
console.log(generator.next("next3"))
// 执行内部代码:5555 next3
// {value: 'cccc', done: false}
console.log(generator.next())
// {value: undefined, done: true}
5.3_生成器提前结束 – return函数
给生成器函数传递参数的方法是通过return函数, return传值后这个生成器函数就会结束,之后调用next不会继续生成值了;
function* foo(name1) {
console.log("执行内部代码:1111", name1)
const name2 = yield "aaaa"
console.log("执行内部代码:3333", name2)
const name3 = yield "bbbb"
// return "bbbb" //同样的,在生成器函数内部执行return,后面的next返回的value是undefined,done为true
console.log("执行内部代码:5555", name3)
yield "cccc"
console.log("最后一次执行")
return undefined
}
const generator = foo("next1")
// 1.generator.return提前结束函数
console.log(generator.next()) //{value: 'aaaa', done: false}
console.log(generator.return("next2")) //{value: 'next2', done: true}
// 由于生成器调用了return方法,生成器函数提前结束
console.log("-------------------")
console.log(generator.next("next3")) //{value: undefined, done: true}
console.log(generator.next("next4")) //{value: undefined, done: true}
5.4_生成器抛出异常 – throw函数
除了给生成器函数内部传递参数之外,也可以给生成器函数内部抛出异常:
- 抛出异常后可以在生成器函数中捕获异常;
- 虽然在catch语句中不能继续yield新的值了,但是可以在catch语句外使用yield继续中断函数的执行;
function* foo(name1) {
console.log("执行内部代码:1111", name1)
const name2 = yield "aaaa"
console.log("执行内部代码:3333", name2)
const name3 = yield "bbbb"
console.log("执行内部代
console.log("执行内部代码:5555", name3)
yield "cccc"
console.log("最后一次执行")
return undefined
}
const generator = foo("next1")
// 2.generator.throw向函数抛出一个异常
console.log(generator.next())
//执行内部代码:1111 next1
// {value: 'aaaa', done: false}
console.log(generator.throw(new Error("next2 throw error")))
// Uncaught Error: next2 throw error 【浏览器报错,后续代码无法执行】
console.log("-------------------")
console.log(generator.next("next3"))
console.log(generator.next("next4"))
5.5_生成器替代迭代器
生成器是一种特殊的迭代器,那么在某些情况下可以使用生成器来替代迭代器
const names = ["abc", "cba", "nba"]
function* createArrayIterator(arr) {
for (let i = 0; i < arr.length; i++) {
yield arr[i] //arr[i]就是每次生成器的返回值
}
}
//生成器迭代
const namesIterator = createArrayIterator(names)
console.log(namesIterator.next()) //{value: 'abc', done: false}
console.log(namesIterator.next()) //{value: 'cba', done: false}
console.log(namesIterator.next()) //{value: 'nba', done: false}
console.log(namesIterator.next()) //{value: undefined, done: true}
// 2.生成器函数, 可以生成某个范围的值
// [3, 6)
function* createRangeGenerator(start, end) {
for (let i = start; i < end; i++) {
yield i
}
}
const rangeGen = createRangeGenerator(3, 6)
console.log(rangeGen.next()) //{value: 3, done: false}
console.log(rangeGen.next()) //{value: 4, done: false}
console.log(rangeGen.next()) //{value: 5, done: false}
console.log(rangeGen.next()) //{value: undefined, done: true}
事实上还可以使用yield*
来生产一个可迭代对象,相当于是一种yield的语法糖,只不过会依次迭代这个可迭代对象,每次迭代其中的一个值;
// 1.yield*替换之前的方案
const names = ["abc", "cba", "nba"]
function* createArrayIterator(arr) {
yield* arr
}
const namesIterator = createArrayIterator(names)
console.log(namesIterator.next()) //{value: 'abc', done: false}
console.log(namesIterator.next()) //{value: 'cba', done: false}
console.log(namesIterator.next()) //{value: 'nba', done: false}
console.log(namesIterator.next()) //{value: undefined, done: true}
// 2.yield替换类中的实现
class Person {
// 类的构造方法
constructor(name, age, height, friends) {
this.name = name
this.age = age
this.height = height
this.friends = friends
}
// 可迭代对象的特定函数 【注意,符号 * 】
*[Symbol.iterator]() {
yield* this.friends
}
}
// 类的实例对象
const p = new Person("hhh", 18, 1.88, ["kobe", "james", "curry"])
for (const item of p) {
console.log(item) //依次输出kobe james curry
}
const pIterator = p[Symbol.iterator]() //调用类的可迭代对象的特定函数
console.log(pIterator.next()) //{value: 'kobe', done: false}
console.log(pIterator.next()) //{value: 'james', done: false}
console.log(pIterator.next()) //{value: 'curry', done: false}
console.log(pIterator.next()) //{value: undefined, done: true}