什么是遍历器
- 接口,为各种数据结构提供统一访问机制
- 默认具有遍历器的数据结构:数组,Map,Set,Generator函数
- 访问方式:for...of
- 一种数据结构,只要定义了Symbol.iterator属性,则实现了遍历器Interface
- Symbol.iterator可以返回next(), return(), throw()
set 数据结构Iterator使用实例
let sports = new Set().add('Basketball').add('Football').add('Tennis');
console.log(typeof sports[Symbol.iterator]);
console.log(sports[Symbol.iterator]());
for (let sport of sports) {
console.log(sport);
}
为obj添加Iterator
function Respchain(value) {
this.value = value;
this.next = null;
}
Respchain.prototype[Symbol.iterator] = function() {
var iterator = { next: next };
var current = this;
function next() {
if (current) {
var value = current.value;
current = current.next;
return { done: false, value: value };
} else {
return { done: true };
}
}
return iterator;
}
let step1 = new Respchain(1);
let step2 = new Respchain(2);
let step3 = new Respchain(3);
step1.next = step2;
step2.next = step3;
for(let step of step1){
console.log(step);
}
区别for...in
var arr = ['a', 'b', 'c', 'd'];
for (let a in arr) {
console.log(a); // 0 1 2 3
}
for (let a of arr) {
console.log(a); // a b c d
}
遍历器的return()
function readLinesSync(file) {
return {
[Symbol.iterator]() {
return {
next() {
return { done: false };
},
return() {
file.close();
return { done: true };
}
};
},
};
}