每天做个总结吧,坚持就是胜利!
/**
@date 2021-06-01
@description ES6之Iterator使用总结
*/
壹(序)
今天重新看了ES6入门Iterator章节,做个总结。
贰(概念)
Iterator是一种接口机制,本质上就是一个指针对象,用来处理数据结构的遍历操作,所有部署了Iterator接口的数据结构都可以完成遍历操作。
默认部署Iterator接口的数据结构都具有Symbol.iterator属性,这个属性是一个函数,调用后返回一个遍历器,遍历器原型上有一个next函数,调用next函数会返回一个对象,对象中包括value和done,value表示当前的值,done表示是否遍历完成。
比如{ value: 1, done: false }表示当前值为1,遍历未完成,{ value: undefined, done: true }表示已经遍历完成,当前没有值,value为undefined。
默认部署Iterator接口的数据结构:
- Array;
- Map;
- Set;
- String;
- NodeList;
- arguments;
- TypedArray;
叁(作用)
Iterator有以下三个作用:
- 为各种不同的数据结构提供统一的访问接口;
- 让数据结构成员按照某种次序排列;
- 使用
for...of遍历数据结构;
肆(过程)
Iterator的遍历过程如下:
- 创建一个
指针对象,指向当前数据结构的第一项; - 调用指针的
next方法,指向数据结构的第二项; - 不断调用
next方法,直到指针指向结束位置;
伍(实践)
const arr = [1, 2, 3, 4];
const iterator = arr[Symbol.iterator]();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: 4, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
// 使用foo...of
for (const item of arr) {
console.log(item); // 1 2 3 4
}
陆(手写实现)
有时候可能需要给Object部署Iterator接口,此时就需要自己手写实现,比如想要按属性名首字母第一位排序对一个对象进行遍历:
const obj = {
name: 'E1e',
age: 18,
hobbies: ['coding', 'game', 'study'],
occupation: 'Web Developer',
};
obj[Symbol.iterator] = function () {
const self = this;
const sortKeys = Object.keys(self).sort(
(a, b) => a.charCodeAt() - b.charCodeAt()
);
let index = -1;
return {
next: function () {
index++;
return index < sortKeys.length
? { value: self[sortKeys[index]], done: false }
: { value: undefined, done: true };
},
};
};
for (const item of obj) {
console.log(item); // 18 [ 'coding', 'game', 'study' ] 'E1e' 'Web Developer'
}
配合Generator函数实现Iterator接口最简单:
const obj = {
name: 'E1e',
age: 18,
hobbies: ['coding', 'game', 'study'],
occupation: 'Web Developer',
};
obj[Symbol.iterator] = function* () {
const self = this;
const sortKeys = Object.keys(self).sort(
(a, b) => a.charCodeAt() - b.charCodeAt()
);
for (let i = 0; i < sortKeys.length; i++) {
yield this[sortKeys[i]];
}
};
for (const item of obj) {
console.log(item); // 18 [ 'coding', 'game', 'study' ] 'E1e' 'Web Developer'
}
柒(结语)
Iterator还有return和throw方法,这里就不总结了,主要是总结使用。