gpt4 book ai didi

javascript - 有什么方法可以从 indexeddb 中检索随机行

转载 作者:太空狗 更新时间:2023-10-29 15:49:48 25 4
gpt4 key购买 nike

我想从 meals 表中随机检索一行,如何实现?

我的代码:

var transaction = db.transaction(["meals"], "readonly");
var store = transaction.objectStore("meals");
var index = store.index("time"); // to search in the field time type
range = IDBKeyRange.only(3); // 3 means it is a lunch

index.openCursor(range).onsuccess = function (e) {
var dt = event.target.result;
if (dt) {
var s = dt.value['fno1'];
}
};

最佳答案

与其一次前进一行直到您达到随机结果,不如使用 advance(n) 来跳出一组随机结果呢?这是一个完整的例子。它假设有两个按钮来播种数据和调用随机选择。我打算在这个星期一写博客。

/* global $,document,indexedDB,console */

/**
* Returns a random integer between min and max
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

$(document).ready(function() {
var db;

var openRequest = indexedDB.open("randomidb",1);

openRequest.onupgradeneeded = function(e) {
var thisDB = e.target.result;

console.log("running onupgradeneeded");

if(!thisDB.objectStoreNames.contains("notes")) {
thisDB.createObjectStore("notes", {autoIncrement:true});
}
};


openRequest.onsuccess = function(e) {
console.log("running onsuccess");

db = e.target.result;

$("#seedButton").on("click", function() {

var store = db.transaction(["notes"],"readwrite").objectStore("notes");

for(var i=0; i<10; i++) {
var note = {
title:"Just a random note: "+getRandomInt(1,99999),
created:new Date()
};

var request = store.add(note);

request.onerror = function(e) {
console.log("Error",e.target.error.name);
//some type of error handler
};

request.onsuccess = function(e) {
console.log("Woot! Did it");
};
}

});

$("#randomButton").on("click", function() {

//success handler, could be passed in
var done = function(ob) {
console.log("Random result",ob);
};

//ok, first get the count
var store = db.transaction(["notes"],"readonly").objectStore("notes");

store.count().onsuccess = function(event) {
var total = event.target.result;
var needRandom = true;
console.log("ok, total is "+total);
store.openCursor().onsuccess = function(e) {
var cursor = e.target.result;
if(needRandom) {
var advance = getRandomInt(0, total-1);
console.log("going up "+advance);
if(advance > 0) {
needRandom = false;
cursor.advance(advance);
} else {
done(cursor);
}
} else {
done(cursor);
}

};

};

});

};

});

关于javascript - 有什么方法可以从 indexeddb 中检索随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27124058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com