目录
迭代器
1.什么是迭代器
迭代器是帮助我们对某个数据结构进行遍历的对象。
在JavaScript中,迭代器也是一个具体的对象,这个对象需要符合迭代器协议,那么在js中这个标准就是一个特定的next方法;
next方法有如下要求:
- next方法是一个有一个参数或无参数的函数,该函数返回一个拥有以下两个属性的对象;
- done(boolean):
-
- 如果迭代器可以产生序列中的下一个值,则为 false。(这等价于没有指定 done 这个属性。)
- 如果迭代器已将序列迭代完毕,则为 true。这种情况下,value 是可选的,如果它依然存在,即为迭代结束之后的默认返回值。
- value:
-
- 迭代器返回的任何 JavaScript 值。done 为 true 时可省略。
编写一个符合规则的迭代器:
// 编写一个符合规则的迭代器
const iterator = {
next: function() {
return { // 返回一个拥有这两个属性的对象
done: true,
value: 123
}
}
}
2.迭代器的基本使用
创建一个迭代器对象来访问数组:
// 数组
const names = ['a', 'b', 'c', 'd']
// 用于记录遍历时的下标
let index = 0
// 创建一个迭代器对象来访问数组
const namesIterator = {
next: function() {
if (index < names.length) {
return { done: false, value: names[index++]}
} else {
return { done: true, vlaue: undefined}
}
}
}
console.log(namesIterator.next()); // { done: false, value: 'a' }
console.log(namesIterator.next()); // { done: false, value: 'b' }
console.log(namesIterator.next()); // { done: false, value: 'c' }
console.log(namesIterator.next()); // { done: false, value: 'd' }
console.log(namesIterator.next()); // { done: true, vlaue: undefined }
console.log(namesIterator.next()); // { done: true, vlaue: undefined }
封装一个迭代器函数:
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 namea = ['a', 'b', 'c']
const ages = [1, 2, 3]
const nameaIterator = createArrayIterator(namea)
const agesIterator = createArrayIterator(ages)
console.log(nameaIterator.next()); // { done: false, value: 'a' }
console.log(nameaIterator.next()); // { done: false, value: 'b' }
console.log(nameaIterator.next()); // { done: false, value: 'c' }
console.log(nameaIterator.next()); // { done: true, value: undefined }
console.log(agesIterator.next()); // { done: false, value: 1 }
console.log(agesIterator.next()); // { done: false, value: 2 }
console.log(agesIterator.next()); // { done: false, value: 3 }
console.log(agesIterator.next()); // { done: true, value: undefined }
3.可迭代对象
可迭代对象的要求是必须实现 @@iterator 方法,在代码中我们使用 Symbol.iterator 访问该属性,实现了该方法的对象为可迭代对象;
当一个对象变成一个可迭代对象的时候,进行某些迭代操作,比如 for…of 操作时,其实就会调用它的 @@iterator 方法;
// 创建一个可迭代对象
const iterableObj = {
names: ['a', 'b', 'c'],
[Symbol.iterator]: function() {
let index = 0
return {
next: () => { // 这里必须是箭头函数: 为了this的指向iterableObj对象,而不是return的迭代器对象
if (index < this.names.length) {
return { done: false, value: this.names[index++]}
} else {
return { done: true, value: undefined}
}
}
}
}
}
console.log(iterableObj[Symbol.iterator]); // [Function: [Symbol.iterator]]
// 每次调用iterableObj[Symbol.iterator]()函数都是独立的,一次调用的next不会影响另一此调用的next
const iterator1 = iterableObj[Symbol.iterator]() // 这里必须要有 () ,这样才是调用这个函数
console.log(iterator1.next()); // { done: false, value: 'a' }
console.log(iterator1.next()); // { done: false, value: 'b' }
console.log(iterator1.next()); // { done: false, value: 'c' }
console.log(iterator1.next()); // { done: false, value: undefined }
// 第二此调用
const iterator2 = iterableObj[Symbol.iterator]() // 这里必须要有 () ,这样才是调用这个函数
console.log(iterator2.next()); // { done: false, value: 'a' }
console.log(iterator2.next()); // { done: false, value: 'b' }
console.log(iterator2.next()); // { done: false, value: 'c' }
console.log(iterator2.next()); // { done: false, value: undefined }
// for of 就是调用了iterableObj的iterableObj[Symbol.iterator]()函数
for (const item of iterableObj) {
console.log(item);
}
4.内置可迭代对象
事实上我们平时创建的很多原生对象已经实现了可迭代协议,会生成一个迭代器对象的:
String、Array、Map、Set、arguments对象、NodeList集合;
// String、Array、Map、Set、arguments对象、NodeList集合是可迭代对象,他们内置了迭代器
// 如字符串就是一个可迭代对象
const strings = 'abc'
// 获取可迭代的函数
console.log(strings[Symbol.iterator]); // [Function: [Symbol.iterator]]
// 调用可迭代函数, 获取迭代器
const iteratorString = strings[Symbol.iterator]() // 别忘了这里的(),调用可迭代函数
console.log(iteratorString.next()); // { value: 'a', done: false }
console.log(iteratorString.next()); // { value: 'b', done: false }
console.log(iteratorString.next()); // { value: 'c', done: false }
console.log(iteratorString.next()); // { value: undefined, done: false }
5.可迭代对象的应用
- 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.for of场景
// 2.展开语法(spread syntax)
const iterableObj = {
names: ["abc", "cba", "nba"],
[Symbol.iterator]: function() {
let index = 0
return {
next: () => {
if (index < this.names.length) {
return { done: false, value: this.names[index++] }
} else {
return { done: true, value: undefined }
}
}
}
}
}
const names = ["abc", "cba", "nba"]
const newNames = [...names, ...iterableObj]
console.log(newNames)
const obj = { name: "why", age: 18 }
// for (const item of obj) {
// }
// ES9(ES2018)中新增的一个特性: 用的不是迭代器
const newObj = { ...obj } // 由于对象没有可迭代器,所以这里不是可迭代对象的应用
console.log(newObj)
// 3.解构语法
const [ name1, name2 ] = names
// const { name, age } = obj 不一样ES9新增的特性
// 4.创建一些其他对象时
const set1 = new Set(iterableObj)
const set2 = new Set(names)
const arr1 = Array.from(iterableObj)
// 5.Promise.all
Promise.all(iterableObj).then(res => {
console.log(res)
})
6.自定义类的迭代
在类中实现[Symbol.iterator]函数。
7.迭代器的中断
迭代器在某些情况下会在没有完全迭代的情况下中断:
- 比如遍历的过程中通过break、continue、return、throw中断了循环操作;
- 比如在解构的时候,没有解构所有的值;
那么这个时候我们想要监听中断的话,可以添加return方法:
class Classroom {
constructor(address, name, students) {
this.address = address
this.name = name
this.students = students
}
entry(newStudent) {
this.students.push(newStudent)
}
[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}
}
}
}
}
const classroom = new Classroom('13-304', "教室", ['jabes', 'dfsaf', 'tjx'])
classroom.entry('jiying')
for (const stu of classroom) {
console.log(stu);
if (stu === 'tjx') break // 这里监听被中断,然后会执行return中的监听中断的代码
}
生成器
生成器是ES6中新增的一种函数控制、使用的方案,它可以让我们更加灵活的控制函数什么时候继续执行、暂停执 行等。
1.生成器函数
生成器函数也是一个函数,但是和普通的函数有一些区别:
- 首先,生成器函数需要在function的后面加一个符号:*****
- 其次,生成器函数可以通过yield关键字来控制函数的执行流程:
- 最后,生成器函数的返回值是一个Generator(生成器):生成器事实上是一种特殊的迭代器;
function* foo() {
console.log("函数开始执行");
const value1 = 100
console.log("第一段代码:", value1);
yield
const value2 = 200
console.log("第二段代码:", value2);
yield
const value3 = 300
console.log("第三段代码:", value3);
yield
console.log("函数执行结束(相当于第四段代码");
}
// 调用生成器函数,会返回一个生成器对象
const generator = foo()
// 执行第一段代码
generator.next()
// 执行第二代代码
generator.next()
// 一次类推
generator.next()
generator.next()
generator.next()
// 输出如下:实际上generator.next()有返回值
// 函数开始执行
// 第一段代码: 100
// 第二段代码: 200
// 第三段代码: 300
// 函数执行结束(相当于第四段代码
2.生成器函数执行
生成器函数foo的执行体压根没有执行,它只是返回了一个生成器对象。
通过调用next让它执行函数中的代码,yield为分隔;
迭代器的next是会有返回值的,但是我们很多时候不希望next返回的是一个undefined,这个时候我们可以通过yield来返回结果,即yield后面跟一个值;
// 当遇到yield时候值 暂停 函数的执行
// 当遇到return时候生成器就 停止 执行
function* foo() {
console.log("函数开始执行~")
const value1 = 100
console.log("第一段代码:", value1)
yield // 如果yield这里后面跟值,则会是value的值,不跟值则为undefined
const value2 = 200
console.log("第二段代码:", value2)
yield value2
const value3 = 300
console.log("第三段代码:", value3)
yield value3
console.log("函数执行结束~")
return "123"
}
// generator本质上是一个特殊的iterator
const generator1 = foo()
console.log("返回值1:", generator1.next())
console.log("返回值2:", generator1.next())
console.log("返回值3:", generator1.next())
console.log("返回值3:", generator1.next())
// 多出来的next
console.log("返回值3:", generator1.next())
console.log("返回值3:", generator1.next())
// 输出如下:
// 函数开始执行~
// 第一段代码: 100
// 返回值1: { value: undefined, done: false } // 这里undefined的原因是yield后面没有跟值
// 第二段代码: 200
// 返回值2: { value: 200, done: false }
// 第三段代码: 300
// 返回值3: { value: 300, done: false }
// 函数执行结束~
// 返回值3: { value: '123', done: true }
// 返回值3: { value: undefined, done: true }
// 返回值3: { value: undefined, done: true }
3.生成器传递参数
调用next函数的时候,可以给它传递参数,那么这个参数会作为上一个yield语句的返回值; 注意:也就是说我们是为本次的函数代码块执行提供了一个值;
function* foo(num) {
console.log("函数开始执行");
const value1 = 100 * num
console.log("第一段代码:", value1);
const n = yield value1 // 这里的value1为第一段代码的value值,不受第二段代码next传递参数的影响
const value2 = 200 * n
console.log("第二段代码:", value2);
const count = yield value2 // value:2000
const value3 = 300 * count
console.log("第三段代码:", value3);
yield value3
console.log("最后一段代码");
return '123'
}
// 生成器上的next方法可以传递参数
const generator = foo(10)
// 第一段代码
console.log(generator.next());
// 第二段代码
console.log(generator.next(10)); // 这里传入的参数会成为第一段代码的yield的返回值
// 第三段代码
console.log(generator.next(10));
// 第四段代码
console.log(generator.next()); // 最后一段代码的return值将作为这里的value值
// 输出如下:
// 函数开始执行
// 第一段代码: 1000
// { value: 1000, done: false }
// 第二段代码: 2000
// { value: 2000, done: false }
// 第三段代码: 3000
// { value: 3000, done: false }
// 最后一段代码
// { value: '123', done: true }
4.生成器提前结束
还有一个可以给生成器函数传递参数的方法是通过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 generator1 = foo(10)
// 第一段代码
console.log(generator1.next())
// 相当于在第一段代码的后面添加了return语句,提前终止生成器代码的执行
console.log(generator1.return('sdf')) // return要有参数,作为value的值
console.log(generator1.next())
console.log(generator1.next())
// 输出如下:
// 函数开始执行~
// 第一段代码: 1000
// { value: 1000, done: false }
// { value: 'sdf', done: true }
// { value: undefined, done: true }
// { value: undefined, done: true }
5.生成器抛出异常
除了给生成器函数内部传递参数之外,也可以给生成器函数内部抛出异常:
抛出异常后我们可以在生成器函数中捕获异常;
但是在catch语句中不能继续yield新的值了,但是可以在catch语句外使用yield继续中断函数的执行;
function* foo() {
console.log("代码开始执行");
const value1 = 100
try {
yield value1
} catch (err) {
console.log("捕获到异常:", err);
}
console.log("第二段代码继续执行");
const value2 = 200
yield value2
console.log("代码执行结束");
}
const generator2 = foo()
console.log(generator2.next());
console.log(generator2.throw('err message'));
console.log(generator2.next());
// 输出如下:
// 代码开始执行
// { value: 100, done: false }
// 捕获到异常: err message
// 第二段代码继续执行
// { value: 200, done: false }
// 代码执行结束
// { value: undefined, done: true }
6.生成器替代迭代器
可以使用yield*来生产一个可迭代对象: 这个时候相当于是一种yield的语法糖,只不过会依次迭代这个可迭代对象,每次迭代其中的一个值;
// 一、生成器替代迭代器
function* createArrayIterator(arr) {
// 1.写法一
// yield 'abc'
// yield 'cba'
// yield 'nba'
// 2.写法二
// for (const item of arr) {
// yield item
// }
// 3.写法三
yield* arr // yield*后面必须是可迭代对象
}
const nameg = ['abc', 'cba', 'nba']
const namegIterator = createArrayIterator(nameg)
console.log(namegIterator.next()); // { value: 'abc', done: false }
console.log(namegIterator.next()); // { value: 'cba', done: false }
console.log(namegIterator.next()); // { value: 'nba', done: false }
console.log(namegIterator.next()); // { value: undefined, done: true }
// 二、创建一个函数, 这个函数可以迭代一个范围内的数字
function* createRangeIterator(start, end) {
let index = start
while (index < end) {
yield index++
}
}
const rangIterator = createRangeIterator(10, 13)
console.log(rangIterator.next()); // { value: 10, done: false }
console.log(rangIterator.next()); // { value: 11, done: false }
console.log(rangIterator.next()); // { value: 12, done: false }
console.log(rangIterator.next()); // { value: undefined, done: true }
// 三、class案例
class Classroom {
constructor(address, name, students) {
this.address = address
this.name = name
this.students = students
}
entry(newStudent) {
this.students.push(newStudent)
}
// [Symbol.iterator] = function*() {
// yield* this.students
// }
*[Symbol.iterator]() {
yield* this.students
}
}
const classroom = new Classroom("3幢", "1102", ["abc", "cba"])
for (const item of classroom) {
console.log(item)
}
7.异步代码的处理方案
// 需求:
// 1> url: why -> res: why
// 2> url: res + "aaa" -> res: whyaaa
// 3> url: res + "bbb" => res: whyaaabbb
function requestData(url) {
return new Promise((resovle, rejest) => {
// 模拟网络请求
setTimeout(() => {
// 拿到请求的结果
resovle(url)
}, 2000)
})
}
// 方案一:多次回调
// requestData("why").then(res => {
// requestData(res + 'aaa').then(res => {
// requestData(res + 'bbb').then(res => {
// console.log(res); // 6秒后输出 whyaaabbb
// })
// })
// })
// // 方案二:Promise中的then解决
// requestData('why').then(res => {
// return requestData(res + 'aaa')
// }).then(res => {
// return requestData(res + 'bbb')
// }).then(res => {
// console.log(res);
// })
// 方案三:Promise + generator 实现
function* getData() {
const res1 = yield requestData('why')
const res2 = yield requestData(res1 + 'aaa')
const res3 = yield requestData(res2 + 'bbb')
console.log(res3);
}
// 1.手动执行生成器函数
// const generatora = getData()
// generatora.next().value.then(res => { // 这个then的res为why
// generatora.next(res).value.then(res => { // 这个then的res为whyaaa
// generatora.next(res).value.then(res => { // 这个then的res为whybbb
// generatora.next(res) // 这里直接输出
// })
// })
// })
// 2.自己封装一个自动执行的函数
// function execGenerator(genFn) {
// const generator = genFn()
// function exec(res) {
// const result = generator.next(res)
// if (result.done) {
// return result.value
// }
// result.value.then(res => {
// exec(res) // 递归
// })
// }
// exec()
// }
// execGenerator(getData)
// 3.使用第三方包:co 自动执行(async与await出现以前常用这方法)
// TJ: co/n(nvm)/commander(coderwhy/vue cli)/express/koa(egg)
// const co = require('co')
// co(getData)
// 方案四:async/await
async function getData() {
const res1 = await requestData('why')
const res2 = await requestData(res1 + 'aaa')
const res3 = await requestData(res2 + 'bbb')
console.log(res3);
}
getData()