首先我们以数组为例, 我们要知道迭代器迭代的原理,也就是为什么可以支持类似于 for....of的循环语法。
迭代器遍历对象原理,看一下下面这个代码,我们发现了迭代器这个玩意,整个过程很类似for...of的过程,只不过我们没有去循环而是一次一次的调用 迭代器.next()
const arr1=[1,2,3,4,5];
let ite=arr1[Symbol.iterator](); //重要的是这个迭代器
console.log(ite.next())//{ value: 1, done: false }
console.log(ite.next())//{ value: 2, done: false }
console.log(ite.next())//{ value: 3, done: false }
console.log(ite.next())//{ value: 4, done: false }
console.log(ite.next())//{ value: 5, done: false }
console.log(ite.next())//{ value: undefined, done: true }
迭代原理: 实现对象的 迭代器方法 , [Symbol.iterator]
下面我们通过实现迭代器,让我们自己的对象支持for....of 语法 ,代码1和代码是两种实现
第一种实现:
class ClassStudentList {
stus = ["张三", "李四", "王五", "陈六"];
#index = 0;
constructor() {
}
//迭代器实现 用于支持for....of
[Symbol.iterator]() {
let $this = this;
return{
next:()=>{
if ($this.#index < $this.stus.length) {
const ret = {value: $this.stus[$this.#index], done: false};
$this.#index++;
return ret;
} else {
return {value: undefined, done: true};
}
}
};
}
}
//创建对象
let classInfo=new ClassStudentList();
//遍历对象
for(let stu of classInfo){
console.log(stu)
}
第二种实现:
class ClassStudentList {
stus = ["张三", "李四", "王五", "陈六"];
#index = 0;
constructor() {
}
//迭代器实现 function*()实现 用于支持for....of
[Symbol.iterator]=function *() {
let $this = this;
for(let v of $this.stus){
yield v;
}
}
}
//创建对象
let classInfo=new ClassStudentList();
//遍历对象
for(let stu of classInfo){
console.log(stu)
}
结果输出