// 创建数组
const arr = [1, 2, 3, 4, 5];
// 创建迭代器对象
const iterator = {
index: 0,
next() {
if (this.index < arr.length) {
return {
value: arr[this.index++],
done: false
};
} else {
return {
value: undefined,
done: true
};
}
}
};
// 使用迭代器
let result = iterator.next();
while (!result.done) {
console.log(result.value);
result = iterator.next();
}
原理解释
- 创建数组:首先定义了要遍历的数组
arr
,值为 [1, 2, 3, 4, 5]
。
- 创建迭代器对象:
index
属性:用于记录当前遍历到数组的位置,初始值为0。
next
方法:每次调用next
方法时:
- 首先判断
index
是否小于数组的长度。如果小于,说明还没有遍历完数组,返回一个包含value
(当前数组元素)和done
(表示是否遍历结束,这里为false
)的对象,并将index
自增1。
- 如果
index
大于或等于数组长度,说明数组已遍历完,返回一个value
为undefined
,done
为true
的对象。
- 使用迭代器:
- 先调用一次
iterator.next()
获取第一个值,返回的结果保存在result
中。
- 使用
while
循环,只要result.done
为false
,就说明还没遍历完,打印当前的result.value
,然后再次调用iterator.next()
获取下一个值并更新result
,直到result.done
为true
,此时数组遍历结束。