我想对从indexedDB获得的结果进行排序 每条记录都有{id,text,date}结构,其中'id'是keyPath。
我想按日期对结果进行排序。
我目前的代码如下:
var trans = db.transaction(['msgs'], IDBTransaction.READ);
var store = trans.objectStore('msgs');
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound("");
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false){
return;
}
console.log(result.value);
result.continue();
};
答案 0 :(得分:18)
实际上,您必须索引date
objectStore中的msgs
字段,并在objectStore上打开索引游标。
var cursorRequest = store.index('date').openCursor(null, 'next'); // or prev
这将获得排序结果。这就是应该如何使用索引。
答案 1 :(得分:8)
这是Josh提出的更有效的方法。
假设您在“日期”上创建了一个索引:
// Use the literal "readonly" instead of IDBTransaction.READ, which is deprecated:
var trans = db.transaction(['msgs'], "readonly");
var store = trans.objectStore('msgs');
var index = store.index('date');
// Get everything in the store:
var cursorRequest = index.openCursor();
// It's the same as:
// var cursorRequest = index.openCursor(null, "next");
// Or, if you want a "descendent ordering":
// var cursorRequest = index.openCursor(null, "prev");
// Note that there's no need to define a key range if you want all the objects
var res = new Array();
cursorRequest.onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) {
res.push(cursor.value);
cursor.continue();
}
else {
//print res etc....
}
};
有关光标方向的更多信息:http://www.w3.org/TR/IndexedDB/#cursor-concept
IDBIndex API位于:http://www.w3.org/TR/IndexedDB/#idl-def-IDBIndex
答案 2 :(得分:-3)
感谢javascript irc的zomg,hughfdjackson,我对最终的数组进行了排序。修改后的代码如下:
var trans = db.transaction(['msgs'], IDBTransaction.READ);
var store = trans.objectStore('msgs');
// Get everything in the store;
var keyRange = IDBKeyRange.lowerBound("");
var cursorRequest = store.openCursor(keyRange);
var res = new Array();
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false){
**res.sort(function(a,b){return Number(a.date) - Number(b.date);});**
//print res etc....
return;
}
res.push(result.value);
result.continue();
};