可迭代接口,使用迭代器模式实现对象for...of遍历
文章目录
实现iterator接口就是for...of前提
Array,Set,Map都可以用for...of来遍历。
通过打印他们的原型对象,都可以看到他们的原型方法中都有iterator方法
通过调用其中的iterator方法,
可以猜测他的实现内部维护了一个数据指针,每次调用next()方法,指针会后移一位,而done属性用来判断数据是否被全部遍历完。
所有可以用for...of遍历的数据类型内部都要实现iterator的接口。这个方法要返回一个next()方法的对象,调用next()方法就可以实现对数据的遍历。
使用迭代器模式实现对象的for...of方法
const obj = {
store: [1, 2, 3, 4],
[Symbol.iterator]: function () {
const self = this;
let index = 0;
return {
next: function () {
const result = {
value: self.store[index],
done: index >= self.store.length
}
index++;
return result;
}
}
}
}
for (let i of obj) {
console.log(i)
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论