js 实现游标
游标的基本概念
游标(Cursor)在JavaScript中通常指代一种数据遍历机制,尤其在数据库操作或大型数据集处理时,用于逐条访问数据而不一次性加载全部内容。前端场景下,游标可能通过IndexedDB或fetch API的分块读取实现。

使用IndexedDB实现游标
IndexedDB是浏览器内置的数据库,支持游标遍历对象存储(Object Store)中的数据:

const request = indexedDB.open('myDatabase', 1);
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction('myStore', 'readonly');
const store = transaction.objectStore('myStore');
const cursorRequest = store.openCursor();
cursorRequest.onsuccess = (e) => {
const cursor = e.target.result;
if (cursor) {
console.log('当前数据:', cursor.value); // 处理当前数据
cursor.continue(); // 移动到下一条记录
}
};
};
使用Fetch API实现分块读取
通过Response.body的ReadableStream逐块处理网络响应,模拟游标行为:
fetch('https://example.com/large-data')
.then(response => {
const reader = response.body.getReader();
function readChunk() {
return reader.read().then(({ done, value }) => {
if (done) return;
console.log('数据块:', new TextDecoder().decode(value));
readChunk(); // 递归读取下一块
});
}
return readChunk();
});
自定义数组游标
对于数组数据,可通过闭包维护当前位置实现游标:
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
console.log(cursor.next().value); // 输出2
注意事项
- 性能:游标适用于大规模数据,避免内存溢出。
- 异步处理:IndexedDB和Fetch游标均为异步操作,需通过回调或Promise处理。
- 错误处理:添加
onerror事件监听以捕获可能的异常。






