// 有限迭代器
function createArrayIterator(arr) {
let index = 0;
return {
next() {
if (index < arr.length) {
return { done: false, value: arr[index++] }
}
return { done: true, value: undefined }
}
}
}
const names = ['a', 'b']
const nums = [1, 2]
const namesIterator = createArrayIterator(names);
const numsIterator = createArrayIterator(nums);
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(namesIterator.next());
console.log(numsIterator.next());
console.log(numsIterator.next());
console.log(numsIterator.next());
console.log(numsIterator.next());
// 无限迭代器
function createInfiniteArrayIterator() {
let index = 0;
return {
next() {
return { done: false, value: index++ }
}
}
}
const infiniteArrayIterator = createInfiniteArrayIterator();
console.log(infiniteArrayIterator.next());
console.log(infiniteArrayIterator.next());
console.log(infiniteArrayIterator.next());
console.log(infiniteArrayIterator.next());
// 创建可迭代对象(什么是可迭代对象?)
const iteratorObj = {
names: ['a', 'b', 'c'],
[Symbol.iterator]: function () {
let index = 0;
return {
next: () => {
if (index < this.names.length) {
return { done: false, value: this.names[index++] }
}
return { done: true, value: undefined }
}
}
}
}
const iterator = iteratorObj[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
// 此时iteratorObj是一个可迭代对象,像for of遍历的是一个可迭代对象,如果是普通对象({a: 1}),使用for of进行遍历时会报错
for (const item of iteratorObj) {
// 1. 输出的值其实是iterator.next().value
// 2. 当done为true时, 停止遍历, 因此item的值只会输出a,b,c
console.log(item);
}
// 创建一个可迭代类
class Classroom {
constructor (name, age, students) {
this.name = name;
this.age = age;
this.students = students;
}
entry(newStudent) {
this.students.push(newStudent)
}
[Symbol.iterator]() {
let index = 0;
return {
next: () => {
if (index < this.students.length) {
return {done: false, value: this.students[index++]}
}
return {done: true, value: undefined}
},
return: () => {
console.log('监听到提前停止了')
return {done: true, value: undefined}
}
}
}
}
const classroom = new Classroom('3橦', 205, ['aaa', 'bbb', 'ccc']);
classroom.entry('ddd')
for (const item of classroom) {
console.log(item);
if (item === 'ccc') break; // 监听迭代器停掉了,在return方法内
}