JS Symbol.Iterator 迭代器
简洁遍历迭代器
const arr = [1, 2, 3, 4, 5, 6]
// 执行一个迭代器 赋值给 iterator 变量
const iterator = arr[Symbol.iterator]();
// 使用 while 循环 先执行一次
let next = iterator.next()
while (!next.done) {
console.log(next.value)
next = iterator.next()
};
手动封装一个 iterator 迭代器
function muddyIterator(arr) {
let index = 0
return {
next() {
return index < arr.length ? {
value: arr[index++],
done: false
} : {
value: undefined,
done: true
}
}
}
}
// 利用闭包直接调用
const arr = [1, 2, 3, 4, 5]
const iterator = muddyIterator(arr);
// 用上述操作方法简洁遍历
let next = iterator.next()
while (!next.done) {
console.log(next.value)
next = iterator.next()
};
遍历结构: