对于我的数据库,我在 created_at
上创建了一个名为 time
的索引:
var os = thisDB.createObjectStore(name, { keyPath : "id" });
os.createIndex("time", "created_at", {unique: false });
如你所见,我将时间保存为 unix 整数:
entry['created_at'] = Date.new(entry['created_at']).unix();
var request = sto.add(entry);
因此,最后在控制台中的数据如下所示:
我的问题是如何获取按方向创建的 asc
或 desc
中的所有数据:
因为当我用光标浏览数据时:
function open_cursor(){
var objectStore = ENTRYDB.transaction('entries').objectStore('entries').index('time');
var request = objectStore.openCursor();
request.onsuccess = function(event) {handle_open(event)};
}
function handle_open(evt){
var cursor = evt.target.result;
if (cursor) {
console.log(cursor.value);
cursor.continue();
}
}
不是按照创建时间排序的!这是随机的!谢谢
最佳答案
您可以通过给 openCursor 函数提供第二个参数来对它进行升序/降序排序:index.openCursor(undefined, "next");或“prev”表示降序。
排序应该对索引起作用,即使您不提供下一个或上一个(下一个是默认值)。当您在索引上调用 openCursor 时,它会以与单击调试器中的“时间”索引时 chrome-dev-tools 显示它们相同的方式循环它们。
您是否使用过 shim(可能适用于 iOS/android)? ( https://github.com/axemclion/IndexedDBShim ),因为这是一个已知问题,排序在那里实际上不起作用。如果您不确定,那么我想这一段不适用于您..
编辑您可能没有使用垫片,因为我从 chrome 开发工具中看到了 indexedDb 的屏幕截图,而在使用垫片时您无法做到这一点,因为它使用了不同的存储机制) .
关于javascript - indexedDB 中按数字/日期排序的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26546716/