IDBKeyRange.bound用于IndexedDB中定义键的闭或半开区间范围,参数为lower、upper及两个布尔值控制开闭,默认闭区间;需确保索引为数值型且类型严格匹配,避免字符串化数字或非法值。

IDBKeyRange.bound 用于在 IndexedDB 中精确指定一个闭区间(或半开区间)的键范围,特别适合数值型索引的范围查询,比如查“年龄在 18 到 65 之间”“订单金额大于等于 100 且小于 500”的数据。
理解 bound 的参数含义
IDBKeyRange.bound(lower, upper, lowerOpen = false, upperOpen = false) 接收四个参数:
- lower:下界值(含或不含取决于 lowerOpen)
- upper:上界值(含或不含取决于 upperOpen)
- lowerOpen:true 表示下界不包含该值(即 >),false 表示包含(即 ≥),默认 false
- upperOpen:true 表示上界不包含该值(即
例如:IDBKeyRange.bound(18, 65) 等价于 [18, 65](含两端);IDBKeyRange.bound(100, 499, false, true) 表示 [100, 499)。
确保索引支持数值范围查询
必须在目标 objectStore 上为数值字段(如 age、price)建立数值型索引,且不能是多字段复合索引中非首项(否则无法高效范围扫描):
- 创建时用
objectStore.createIndex('ageIdx', 'age', { unique: false }) - 查询时用该索引的
index.openCursor(range)或index.getAll(range) - 避免对字符串化数字(如 "25")建索引——会导致字典序比较("100"
执行范围查询的典型代码
以查 age 在 [20, 35] 的用户为例:
const transaction = db.transaction(['users'], 'readonly');
const store = transaction.objectStore('users');
const index = store.index('ageIdx');
const range = IDBKeyRange.bound(20, 35);
const request = index.openCursor(range);
request.onsuccess = function () {
const cursor = request.result;
if (cursor) {
console.log(cursor.value); // 匹配的用户对象
cursor.continue();
}
};
若要一次性获取所有结果,可用 index.getAll(range)(注意内存和性能,大数据集慎用)。
边界与类型需严格匹配
IDBKeyRange 对键类型敏感。如果索引键是 number,传 string(如 "25")会失败或返回空;反之亦然:
- ✅ 正确:
IDBKeyRange.bound(25, 30)(number 值匹配 number 索引) - ❌ 错误:
IDBKeyRange.bound("25", "30")(字符串不会被自动转为数字) - ⚠️ 注意:null、undefined、NaN 不能作为 bound 参数,会抛 TypeError
建议查询前做类型校验:if (typeof low === 'number' && typeof high === 'number') { ... }










