js 实现游标_
游标的基本概念
游标(Cursor)在JavaScript中通常指代一种数据遍历机制,用于逐条处理集合(如数组、数据库查询结果)。前端常见的场景包括遍历DOM元素或异步数据流,后端如Node.js中可能用于数据库查询(如MongoDB的游标)。
数组游标实现
通过维护索引实现数组的逐步访问:

function createArrayCursor(array) {
let index = 0;
return {
next: () => (index < array.length)
? { value: array[index++], done: false }
: { done: true },
reset: () => index = 0
};
}
// 使用示例
const cursor = createArrayCursor([1, 2, 3]);
console.log(cursor.next()); // { value: 1, done: false }
console.log(cursor.next()); // { value: 2, done: false }
异步游标(生成器)
结合生成器函数处理异步数据流:

async function* asyncCursor(dataSource) {
for (const item of dataSource) {
yield await fetchItem(item); // 模拟异步操作
}
}
// 使用示例
(async () => {
const cursor = asyncCursor(['url1', 'url2']);
for await (const item of cursor) {
console.log(item);
}
})();
数据库游标(Node.js + MongoDB)
MongoDB的find()返回游标对象,支持分批获取数据:
const cursor = db.collection('users').find();
cursor.forEach(
doc => console.log(doc),
() => console.log('Done')
);
自定义可迭代游标
实现迭代协议(Iterable Protocol)的游标:
class CustomCursor {
constructor(data) {
this.data = data;
this.index = 0;
}
[Symbol.iterator]() {
return {
next: () => (this.index < this.data.length)
? { value: this.data[this.index++], done: false }
: { done: true }
};
}
}
// 使用示例
const cursor = new CustomCursor(['a', 'b']);
for (const item of cursor) {
console.log(item); // 'a', 'b'
}
注意事项
- 性能:大数据集需分批处理避免内存溢出。
- 资源释放:数据库游标及时关闭(如MongoDB的
cursor.close())。 - 浏览器兼容性:生成器和异步迭代需ES6+环境。
根据需求选择实现方式,数组/异步场景优先考虑生成器,数据库操作直接使用驱动提供的游标API。






