IndexedDB 的 count() 方法可高效统计对象仓库记录数,必须在 readonly 或 readwrite 事务中调用 objectStore.count() 或 index.count(),支持键范围筛选且性能恒定。

IndexedDB 的 count() 方法确实可以快速统计对象仓库中的记录总数,但它不能直接在数据库对象上调用,必须通过游标(cursor)或索引(index)的 count() 方法实现——最常用、最高效的方式是调用 objectStore.count()。
确保使用支持 count() 的 API 版本
count() 是 IDBObjectStore 和 IDBIndex 的实例方法,从现代浏览器(Chrome 23+、Firefox 16+、Safari 10.1+、Edge 12+)开始稳定支持。注意它返回的是 Promise(在 IDB v2+ 的异步上下文中),但传统 callback 方式仍可用。
- 若用 Promise 风格(推荐),需基于
indexedDB.open()成功后的IDBDatabase实例获取IDBObjectStore - 不能在未启动事务或事务已关闭时调用,否则抛出
InvalidStateError - 不支持在只读事务外调用(即必须是
"readonly"或"readwrite"事务)
基础用法:统计整个对象仓库的记录数
最简场景是统计某对象仓库全部条目数量,无需过滤条件:
const request = indexedDB.open("myApp", 1);
request.onsuccess = function(event) {
const db = event.target.result;
const transaction = db.transaction(["users"], "readonly");
const store = transaction.objectStore("users");
const countRequest = store.count();
countRequest.onsuccess = function() {
console.log("总记录数:", countRequest.result); // 如:127
};
countRequest.onerror = function() {
console.error("统计失败", countRequest.error);
}
};
带键范围的精确计数(按条件筛选)
如果只想统计满足某范围条件的记录(比如 id 在 100–200 之间),可传入 IDBKeyRange:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
立即学习“Java免费学习笔记(深入)”;
-
IDBKeyRange.lowerBound(100):≥100 -
IDBKeyRange.upperBound(200):≤200 -
IDBKeyRange.bound(100, 200, false, false):100 ≤ key ≤ 200
示例:
const range = IDBKeyRange.bound(100, 200);
const countRequest = store.count(range);
countRequest.onsuccess = () => console.log("ID 在 100–200 的记录数:", countRequest.result);
使用 Promise 封装更简洁(现代写法)
结合 async/await 可让逻辑更清晰:
async function getCount(dbName, storeName, keyRange = null) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(dbName);
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const db = request.result;
const tx = db.transaction(storeName, "readonly");
const store = tx.objectStore(storeName);
const countReq = keyRange ? store.count(keyRange) : store.count();
countReq.onsuccess = () => resolve(countReq.result);
countReq.onerror = () => reject(countReq.error);
};
});
}
// 调用示例
getCount("myApp", "products").then(total => console.log(total));
相比遍历所有数据再累加,count() 由底层引擎直接返回元信息,性能几乎恒定,无论仓库含百万条还是几条记录,耗时基本一致。

















