遍历器(Iterator)是一种机制(接口):为各种不同的数据结构提供统一的访问机制,任何数据结构只要部署Iterator接口,就可以完成遍历操作「for of循环」,依次处理该数据结构的所有成员
* + 拥有next方法用于依次遍历数据结构的成员
* + 每一次遍历返回的结果是一个对象 {done:false,value:xxx}
* + done:记录是否遍历完成
* + value:当前遍历的结果
*
* 拥有Symbol.iterator属性的数据结构(值),被称为可被遍历的,可以基于for of循环处理
* + 数组
* + 部分类数组:arguments/NodeList/HTMLCollection...
* + String
* + Set
* + Map
* + generator object
* + ...
数组迭代
class Iterator{
constructor(assemble) {
let self = this;
self.assemble = assemble;
self.index = 0
}
next() {
let self = this,
assemble = self.assemble;
if (self.index > assemble.length - 1) {
return {
done: true,
value:undefined
}
}
return {
done: false,
value:this.assemble[self.index++]
}
}
}
let itor = new Iterator([10, 30, 20, 40])
console.log(itor.next());
console.log(itor.next());
console.log(itor.next())
console.log(itor.next())
console.log(itor.next())
对象迭代
let obj = {
name: 'zhufeng',
age: 12,
teacher:'team'
}
//obj[Symbol.iterator]
Object.prototype[Symbol.iterator] = function () {
let assemble = this,
keys = Object.keys(assemble).concat(Object.getOwnPropertySymbols(assemble)),
index = 0;
return {
next() {
if (index > keys.length - 1) {
return {
done: true,
value: undefined
};
}
return {
done: false,
value:assemble[keys[index++]]
}
}
}
}
for (let value of obj) {
console.log(value)
浏览器展示如下:
}
对象迭代:
let obj = {
name: 'zhufeng',
age: 12,
teacher:'team'
}
//obj[Symbol.iterator] 可以给对象添加属性[Symbol.iterator]也可以给对象原型添加属性[Symbol.iterator]
Object.prototype[Symbol.iterator] = function () {
let assemble = this,
keys = Object.keys(assemble).concat(Object.getOwnPropertySymbols(assemble)),
index = 0;
return {
next() {
if (index > keys.length - 1) {
return {
done: true,
value: undefined
};
}
return {
done: false,
value:assemble[keys[index++]]
}
}
}
}
for (let value of obj) {
console.log(value)
}
浏览器输出: