Iterator 的作用
Iterator:遍历器(迭代器),遍历器有如 forEach
、for
等。
寻找 Iterator
console.log(iterator); // 报错
console.log([1, 2][Symbol.iterator]()); // Array Iterator {}
使用 Iterator
我们在控制台打印出上面的 [1, 2][Symbol.iterator]()
,然后展开 :
可以看到有个 next()
的方法,我们来试一下:
const it = [1, 2][Symbol.iterator]();
console.log(it.next()); // {value: 1, done: false}
console.log(it.next()); // {value: 2, done: false}
console.log(it.next()); // {value: undefined, done: true}
归纳:
- 这里的
it
是可遍历对象(可迭代对象) ,必须有next
方法,且返回的值形如上例 Symbol.iterator
是可遍历对象的生成方法
什么是 Iterator
形如上例中 Symbol.iterator (可遍历对象的生成方法)
=> it(可遍历对象)
=> it.next()
=> it.next()
=> … => 直到 done
为 true。这样一个过程称为 Iterator
Iterator 解惑
1.为什么需要 Iterator 遍历器
遍历数组已经有了 for
和 forEach
方法;遍历对象有了 for in
,为什么还需要 Iterator
?
答:Iterator
遍历器是一个统一的遍历方式,既可以遍历数组也可以遍历对象
2.如何更方便地使用 Iterator
我们一般不会直接使用 Iterator 去遍历,而是使用 Iterator 这一套流程封装好之后的 for ... of
for…of的用法
1.认识 for…of
// 不使用 for...of 前使用 Iterator
const arr = [1, 2, 3];
const it = arr[Symbol.iterator]();
let next = it.next();
while(!next.done) {
console.log(next.value);
next = it.next();
console.log(next); // 1 2 3
}
// 使用 for...of
const arr = [1, 2, 3];
for(const item of arr) {
console.log(item); // 1 2 3
}
for…of循环只会遍历出那些 done
为 false
时对应的 value
值
2.与 break、continue 一起使用
使用 for...of
遍历一个数组[1, 2, 3],当遍历到2时停止遍历
const arr = [1, 2, 3];
for (const item of arr) {
if(item === 2) {
break;
}
console.log(item); // 1
}
使用 for...of
遍历一个数组[1, 2, 3],当遍历到2时跳过,继续遍历
const arr = [1, 2, 3];
for (const item of arr) {
if(item === 2) {
continue;
}
console.log(item); // 1 3
}
3.在 for…of 中取得数组的索引
使用ES6中数组新增方法 keys()
const arr = [1, 2, 3];
for(const key of arr.keys()) {
console.log(key); // 0 1 2
}
使用了 Iterator 的场合
除了 for…of 以外还有什么场合使用了 Iterator 呢?
- 数组的展开远算符
只要是原生可遍历就可以使用数组的展开运算符,如 Array、String、Set、Map、arguments、NodeList 等,因为数组的展开远算符底层也是用Iterator
实现的,而这些原生可遍历的数据类型又拥有Iterator
的方法。
console.log(...[1, 2, 3]); // 1 2 3
console.log(...'str'); // s t r
- 数组的解构赋值
const [a, b] = [1, 2];
console.log(a, b); // 1 2
const [a, b] = 'hi';
console.log(a, b); // h i
const [a, b] = new Set([3, 4]);
console.log(a, b); // 3 4
- Set 和 Map的构造函数
// 只要可遍历都可以传入
new Set(iterator)
new Map(iterator) // Map中需要体现键和值,不是单单可遍历就行