1️⃣ 迭代器 ( Iteration )
遍历器(Iterator)就是一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作。
1. ES6 创造了一种新的遍历命令 for...of 循环,Iterator 接口主要供 for...of 消费2. 原生具备 iterator 接口的数据(可用 for of 遍历)1. Array2. Arguments3. Set4. Map5. String6. TypedArray7. NodeList3. 工作原理1. 创建一个指针对象,指向当前数据结构的起始位置2. 第一次调用对象的 next 方法,指针自动指向数据结构的第一个成员3. 接下来不断调用 next 方法,指针一直往后移动,直到指向最后一个成员4. 每调用 next 方法返回一个包含 value 和 done 属性的对象
注: 需要自定义遍历数据的时候,要想到迭代器。
const arr = ['a', 'b', 'c']// 创建一个指针对象,指向当前数据结构的起始位置let iterator = arr[Symbol.iterator]()// 第一次调用对象的 next 方法,指针自动指向数据结构的第一个成员console.log(iterator.next()); // {value: "a", done: false}// 接下来不断调用 next 方法,指针一直往后移动,直到指向最后一个成员console.log(iterator.next()); // {value: "b", done: false}console.log(iterator.next()); // {value: "c", done: false}console.log(iterator.next()); // {value: undefined, done: true}// 每调用 next 方法返回一个包含 value 和 done 属性的对象
2️⃣ 迭代器的应用 - 自定义遍历数据
const obj = {name: "字母",zm: ['a','b','c'],[Symbol.iterator]() {let index = 0;let _this = this;return {next: function () {if (index < _this.zm.length) {const result = { value: _this.zm[index], done: false };// 下标自增index++;// 返回结果return result;} else {return { value: undefined, done: true };}}};}}// 遍历这个对象for (let v of obj) {console.log(v);}
1️⃣ 生成器函数 ( Generator )
生成器函数是 ES6 提供的一种异步编程解决方案,语法行为与传统函数完全不同。
Generator 函数有多种理解角度。语法上,首先可以把它理解成,Generator 函数是一个状态机,封装了多个内部状态。
执行 Generator 函数会返回一个遍历器对象,也就是说,Generator 函数除了状态机,还是一个遍历器对象生成函数。返回的遍历器对象,可以依次遍历 Generator 函数内部的每一个状态。
形式上,Generator 函数是一个普通函数,但是有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态(yield在英语里的意思就是“产出”)。
代码说明:
1. * 的位置没有限制2. 生成器函数返回的结果是迭代器对象,调用迭代器对象的 next 方法可以得到 yield 语句后的值3. yield 相当于函数的暂停标记,也可以认为是函数的分隔符,每调用一次 next 方法,执行一段代码4. next 方法可以传递实参,作为 yield 语句的返回值
function* gen() {console.log(1);yield 'hello';console.log(2);yield 'world';console.log(3);}var hw = gen();/* hw.next(); // 1hw.next(); // 2hw.next(); // 3 */console.log(hw.next());// 1// {value: "hello", done: false}console.log(hw.next());// 2// {value: "world", done: false}console.log(hw.next());// 3// {value: undefined, done: true}// 遍历for (const iterator of gen()) {console.log(iterator);// 1// hello// 2// world// 3}
2️⃣ 生成器函数参数
next 方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值。
function* gen(arg) {// 第一次调用console.log(arg); // AAAlet one = yield 111;// 第二次调用console.log(one); // BBBlet two = yield 222;// 第三次调用console.log(two); // CCClet three = yield 333;// 第四次调用console.log(three); // DDD}var hw = gen('AAA');console.log(hw.next());console.log(hw.next('BBB'));console.log(hw.next('CCC'));console.log(hw.next('DDD'));
2️⃣ 生成器函数实例 - 解决回调地狱
function one() {setTimeout(() => {console.log(1);iterator.next()}, 1000);}function two() {setTimeout(() => {console.log(2);iterator.next()}, 2000);}function three() {setTimeout(() => {console.log(3);}, 3000);}function* gen() {yield one();yield two();yield three();}let iterator = gen()iterator.next()
