JavaScript系列(21)-- Iterator详解
JavaScript Iterator详解 🔄
今天,让我们深入探讨JavaScript中的Iterator(迭代器)。Iterator是ES6引入的重要特性,它为集合类型提供了统一的遍历机制。
Iterator基础概念 🌟
💡 小知识:Iterator是一个对象,它提供了一个next()方法,每次调用都会返回一个包含value和done属性的对象。当遍历完成时,done为true。Iterator是实现可迭代协议的基础。
Iterator的基本实现 📊
// 1. 基本的Iterator实现
class SimpleIterator {
constructor(array) {
this.array = array;
this.index = 0;
}
next() {
if (this.index < this.array.length) {
return {
value: this.array[this.index++],
done: false
};
}
return { value: undefined, done: true };
}
}
// 使用示例
const iterator = new SimpleIterator([1, 2, 3]);
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
// 2. 可迭代对象实现
class IterableCollection {
constructor(items) {
this.items = items;
}
[Symbol.iterator]() {
let index = 0;
const items = this.items;
return {
next() {
return index < items.length
? { value: items[index++], done: false }
: { value: undefined, done: true };
}
};
}
}
// 使用for...of遍历
const collection = new IterableCollection([1, 2, 3]);
for (const item of collection) {
console.log(item); // 1, 2, 3
}
// 3. 无限迭代器
function* infiniteSequence() {
let index = 0;
while (true) {
yield index++;
}
}
const numbers = infiniteSequence();
console.log(numbers.next().value); // 0
console.log(numbers.next().value); // 1
console.log(numbers.next().value); // 2
Iterator的高级应用 🚀
// 1. 自定义迭代器
class Matrix {
constructor(data) {
this.data = data;
}
*[Symbol.iterator]() {
const rows = this.data.length;
const cols = this.data[0].length;
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
yield this.data[i][j];
}
}
}
// 按行迭代
*rowIterator() {
for (const row of this.data) {
yield [...row];
}
}
// 按列迭代
*columnIterator() {
const cols = this.data[0].length;
for (let j = 0; j < cols; j++) {
yield this.data.map(row => row[j]);
}
}
}
// 2. 组合迭代器
class CompositeIterator {
constructor(iterators) {
this.iterators = iterators;
this.currentIndex = 0;
}
*[Symbol.iterator]() {
for (const iterator of this.iterators) {
yield* iterator;
}
}
}
// 3. 过滤迭代器
class FilterIterator {
constructor(iterator, predicate) {
this.iterator = iterator;
this.predicate = predicate;
}
*[Symbol.iterator]() {
for (const item of this.iterator) {
if (this.predicate(item)) {
yield item;
}
}
}
}
Iterator的实用工具 🛠️
// 1. 迭代器工具函数
class IteratorUtils {
// 转换为数组
static toArray(iterator) {
return Array.from(iterator);
}
// 限制迭代次数
static *take(iterator, count) {
let remaining = count;
for (const item of iterator) {
if (remaining <= 0) break;
yield item;
remaining--;
}
}
// 跳过指定数量
static *skip(iterator, count) {
let remaining = count;
for (const item of iterator) {
if (remaining > 0) {
remaining--;
continue;
}
yield item;
}
}
// 映射迭代器
static *map(iterator, mapper) {
for (const item of iterator) {
yield mapper(item);
}
}
// 过滤迭代器
static *filter(iterator, predicate) {
for (const item of iterator) {
if (predicate(item)) {
yield item;
}
}
}
}
// 2. 迭代器链式操作
class IteratorChain {
constructor(iterator) {
this.iterator = iterator;
}
map(mapper) {
this.iterator = IteratorUtils.map(this.iterator, mapper);
return this;
}
filter(predicate) {
this.iterator = IteratorUtils.filter(this.iterator, predicate);
return this;
}
take(count) {
this.iterator = IteratorUtils.take(this.iterator, count);
return this;
}
skip(count) {
this.iterator = IteratorUtils.skip(this.iterator, count);
return this;
}
toArray() {
return IteratorUtils.toArray(this.iterator);
}
}
// 3. 异步迭代器工具
class AsyncIteratorUtils {
static async *map(asyncIterator, mapper) {
for await (const item of asyncIterator) {
yield mapper(item);
}
}
static async *filter(asyncIterator, predicate) {
for await (const item of asyncIterator) {
if (await predicate(item)) {
yield item;
}
}
}
static async toArray(asyncIterator) {
const result = [];
for await (const item of asyncIterator) {
result.push(item);
}
return result;
}
}
Iterator的性能优化 ⚡
// 1. 惰性迭代器
class LazyIterator {
constructor(producer) {
this.producer = producer;
this.cache = [];
this.index = 0;
}
next() {
if (this.index < this.cache.length) {
return {
value: this.cache[this.index++],
done: false
};
}
const { value, done } = this.producer.next();
if (!done) {
this.cache.push(value);
this.index++;
}
return { value, done };
}
[Symbol.iterator]() {
return this;
}
}
// 2. 缓存迭代器
class CachedIterator {
constructor(iterator, cacheSize = 1000) {
this.iterator = iterator;
this.cache = new Map();
this.cacheSize = cacheSize;
}
*[Symbol.iterator]() {
let index = 0;
for (const item of this.iterator) {
if (this.cache.size >= this.cacheSize) {
const firstKey = this.cache.keys().next().value;
this.cache.delete(firstKey);
}
this.cache.set(index, item);
yield item;
index++;
}
}
getCached(index) {
return this.cache.get(index);
}
}
// 3. 批处理迭代器
class BatchIterator {
constructor(iterator, batchSize = 100) {
this.iterator = iterator;
this.batchSize = batchSize;
}
*[Symbol.iterator]() {
let batch = [];
for (const item of this.iterator) {
batch.push(item);
if (batch.length >= this.batchSize) {
yield batch;
batch = [];
}
}
if (batch.length > 0) {
yield batch;
}
}
}
最佳实践建议 💡
- Iterator设计模式
// 1. 迭代器工厂
class IteratorFactory {
static createArrayIterator(array) {
return array[Symbol.iterator]();
}
static createRangeIterator(start, end, step = 1) {
return {
*[Symbol.iterator]() {
for (let i = start; i <= end; i += step) {
yield i;
}
}
};
}
static createObjectIterator(obj) {
return {
*[Symbol.iterator]() {
for (const [key, value] of Object.entries(obj)) {
yield { key, value };
}
}
};
}
}
// 2. 迭代器适配器
class IteratorAdapter {
static toAsyncIterator(iterator) {
return {
async next() {
const { value, done } = iterator.next();
return { value: await value, done };
},
[Symbol.asyncIterator]() {
return this;
}
};
}
static toIterator(asyncIterator) {
return {
next() {
return Promise.resolve(asyncIterator.next());
},
[Symbol.iterator]() {
return this;
}
};
}
}
// 3. 安全迭代器
class SafeIterator {
constructor(iterator) {
this.iterator = iterator;
}
*[Symbol.iterator]() {
try {
yield* this.iterator;
} catch (error) {
console.error('Iterator error:', error);
}
}
}
结语 📝
Iterator是JavaScript中一个强大的特性,它为集合类型提供了统一的遍历机制,并支持惰性计算和异步操作。我们学习了:
- Iterator的基本概念和实现
- 高级Iterator应用
- 实用的Iterator工具
- 性能优化技巧
- 最佳实践和设计模式
💡 学习建议:在使用Iterator时,要注意内存使用和性能优化。合理使用惰性求值和缓存策略,可以显著提升程序性能。同时,要注意处理异常情况,确保迭代器的安全性。
如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇
终身学习,共同成长。
咱们下一期见
💻