ale*_*ods 5 javascript indexeddb
假设我有一个IndexedDB名字的集合items.所有项目都有字段:
revisionfield是一个数字字段.我需要检索具有最大修订值的项目(或者至少只检索最大修订版本值).最好的方法是什么?
Den*_*ski 18
您需要做的第一件事是在revision字段上创建索引.
然后你需要一个搜索函数,它将使用该索引并以对象的逆序打开索引.然后第一个对象将是您要查找的对象.
var index = objectStore.index('revision');
index.openCursor(null, 'prev');
Run Code Online (Sandbox Code Playgroud)
null表示您要搜索的所有值都不是特定值,第二个参数是搜索的方向.
以下是示例代码:
function getMaxNumber (callback) {
var openReq = indexedDB.open(baseName);
openReq.onsuccess = function() {
var db = openReq.result;
var transaction = db.transaction(objectStoreName, 'readonly');
var objectStore = transaction.objectStore(objectStoreName);
var index = objectStore.index('revision');
var openCursorRequest = index.openCursor(null, 'prev');
var maxRevisionObject = null;
openCursorRequest.onsuccess = function (event) {
if (event.target.result) {
maxRevisionObject = event.target.result.value; //the object with max revision
}
};
transaction.oncomplete = function (event) {
db.close();
if(callback) //you'll need a calback function to return to your code
callback(maxRevisionObject);
};
}
}
Run Code Online (Sandbox Code Playgroud)
由于IndexedDBapi是异步的,因此您需要一个回调函数来将值返回给您的代码.
| 归档时间: |
|
| 查看次数: |
4336 次 |
| 最近记录: |