如何获取时间戳值最高的x个对象
How to obtain x objects with highest timestamp value?
我是web应用程序开发的新手,找不到以下问题的解决方案。基本上,我试图从IndexedDB数据库中对最新对象的数组进行排序。每个对象都包含一个时间戳值。我已经在时间戳上创建了一个索引,我能够获得具有最高值的对象。
function getMails (numberOfMessages, _function) {
/* This function uses asynchronous methods, hence you have to pass the key and function that will receive
the messageitem as a parametr */
if (typeof optionalArg === 'undefined') {
optionalArg = 10;
}
function _getMails (db) {
var transaction = db.transaction(["MessageItem"], "readonly");
var store = transaction.objectStore("MessageItem");
var index = store.index("timestamp");
var cursor = index.openCursor(null, 'prev');
var maxTimestampObject = null;
cursor.onsuccess = function(e) {
if (e.target.result) {
maxTimestampObject = e.target.result.value;
_function(maxTimestampObject);
}
};
}
openDB(_getMails);
}
函数openDB打开数据库,并将db对象作为参数传递给_getMails函数。函数getMails当前只传递时间戳值最高的对象。我可以迭代数据库x(numberOfMessages)次,并始终选择时间戳最高的对象,同时排除我试图获取的数组中已经存在的对象。但我不确定这是否是最方便的方式。谢谢你的回复。一月
您只需要在onsuccess
函数中调用cursor.continue()
。它将与下一个光标结果一起被再次调用。
谢谢Kyaw Tun。这是我为那些感兴趣的人准备的最后一个代码:
function openDB(_function) {
// Opening the DB
var openRequest = indexedDB.open("TsunamiDB",1);
openRequest.onupgradeneeded = function(e) {
console.log("Upgrading...");
var thisDB = e.target.result;
if (!thisDB.objectStoreNames.contains("MessageItem")) {
var objectStore = thisDB.createObjectStore("MessageItem");
objectStore.createIndex("timestamp", "envelope.timestamp", {unique:false});
}
}
openRequest.onsuccess = function(e) {
console.log("Success!");
_function(e.target.result);
}
openRequest.onerror = function(e) {
console.log("Error");
console.dir(e);
}}
此函数使用异步方法,因此您必须传递将作为参数接收messageitem的键和函数。Paremetr是x(numberOfMessages)最新消息的数组。对数组进行排序,以便索引为0的消息是最新的消息。
function getMails ( _function, numberOfMessages) {
if (typeof numberOfMessages === 'undefined') {
numberOfMessages = 10;
}
function _getMails (db) {
var transaction = db.transaction(["MessageItem"], "readonly");
var store = transaction.objectStore("MessageItem");
var index = store.index("timestamp");
var objectsArray = [];
var i = 0;
index.openCursor(null, 'prev').onsuccess = function(e) {
var cursor = e.target.result;
if (cursor && i < numberOfMessages) {
objectsArray.push(cursor.value)
++i;
cursor.continue();
}
};
transaction.oncomplete = function(e) {
_function(objectsArray);
}
}
openDB(_getMails);}
相关文章:
- JavaScript JSON关联对象键和值都作为日期时间戳
- 如何按天、周、月对具有时间戳属性的对象进行分组
- 用户如何获取两个时间戳之间的对象
- 如何将 unix 时间戳转换为 JavaScript 日期对象(考虑时区)
- javascript多个对象实例的时间戳相同
- 使用 angular 根据对象的年龄显示不同的时间戳
- RethinkDB - 将导入的 MySQL 时间戳字符串转换为时间对象
- 按时间戳对对象数组进行排序
- 如何存储JSON对象的时间戳
- 如何从UTC时间戳中获取JS Date对象
- 在Javascript中,如何将日期对象转换为epoch时间戳
- 以json对象的形式传递时间戳值以填充流线图
- 从FullCalendar事件对象获取一个简单的时间戳
- Sqlite时间戳到javascript日期对象
- 基于时间戳对JSON对象进行排序
- 如何获取时间戳值最高的x个对象
- 如何在Javascript中循环遍历对象并按时间戳进行分类
- 将postgres时间戳(+时区)转换为Date对象[Javascript]
- 字符串化时间戳对象
- 将unix时间戳转换为javascript日期对象