IndexedBD从上到下选择对象

IndexedBD select objects from upper to lower?

本文关键字:对象 选择 从上到下 IndexedBD      更新时间:2023-11-19

例如:

const customerData = [
  { id: 444, name: "Bill", age: 35, email: "bill@company.com" },
  { id: 5555, name: "Donna", age: 32, email: "donna@home.org" },
  { id: 666, name: "Cat", age: 2, email: "cat@home.org" },
  { id: 888, name: "Gandalf", age: 21000, email: "gandalf@home.org" }
];
function getDataByRange(db, table, index, lower, upper, fun){
    var data = [];
    var tx = db.transaction(table, "readonly");
    var store = tx.objectStore(table);
    var index = store.index(index);
    var boundKeyRange = IDBKeyRange.bound(lower, upper, false, false);
    var request = index.openCursor(boundKeyRange);
    request.onsuccess = function() {
        var cursor = request.result;
        if (cursor) {
            data.push(cursor.value);
            cursor.continue();
        } else {
            fun(data);
        }
    };
}

如何获得下一个结果:甘道夫,比尔,唐娜,猫?

现在我得到的是:猫,唐娜,比尔,甘道夫。

谢谢你的建议!

openCursor方法接受两个参数。第二个参数是可选的,用于指定光标的方向。因为它是可选的,所以您很少看到示例代码中指定的第二个参数,所以这可能就是它令人困惑的原因。

有四个可能的方向值:next、prev、nextUnique和prevUnique。您可以将参数指定为字符串。接下来是隐含的默认参数。

因此,使用openCursor(boundKeyRange, 'prev')反向迭代。