【发布时间】:2014-10-04 19:55:03
【问题描述】:
Here's my test case on JS Bin.
假设您有一个 IndexedDB 对象存储。您的对象非常简单,具有两个属性“a”和“b”。这两个属性都包含整数。并且因为您希望能够在对象存储中查询“a”和“b”的特定值,所以您创建了一个复合索引。以下是此描述之后的一些代码:
var db;
request = indexedDB.open("test", 1);
request.onerror = function (event) { console.log(event); };
request.onupgradeneeded = function (event) {
var db = event.target.result;
db.onerror = function (event) { console.log(event); };
var store = db.createObjectStore("store", {keyPath: "id", autoIncrement: true});
store.createIndex("a, b", ["a", "b"], {unique: true});
store.add({a: 0, b: 0});
store.add({a: 1, b: 0});
store.add({a: 1, b: 1});
};
request.onsuccess = function (event) {
db = request.result;
db.onerror = function (event) { console.log(event); };
};
如果您想从数据库中检索特定对象,这可以正常工作。所以如果你运行这个:
db.transaction("store").objectStore("store").index("a, b").get([1, 0]).onsuccess = function (event) { console.log(event.target.result); };
输出是:
Object {a: 1, b: 0, psid: 2}
太棒了。伟大的。因此,现在您要检索一系列值。比如说,你想将“b”固定为 0,同时让“a”为 0 或 1。现在奇怪的事情开始发生了。试试这个代码:
console.log("[a, b] bound from [0, 0] to [1, 0]");
db.transaction("store").objectStore("store").index("a, b").openCursor(IDBKeyRange.bound([0, 0], [1, 0])).onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
console.log(cursor.value);
cursor.continue();
} else {
console.log("[a, b] bound from [0, 0] to [2, 0]");
db.transaction("store").objectStore("store").index("a, b").openCursor(IDBKeyRange.bound([0, 0], [2, 0])).onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
console.log(cursor.value);
cursor.continue();
}
};
}
};
它产生这个输出:
[a, b] bound from [0, 0] to [1, 0]
Object {a: 0, b: 0, id: 1}
Object {a: 1, b: 0, id: 2}
[a, b] bound from [0, 0] to [2, 0]
Object {a: 0, b: 0, id: 1}
Object {a: 1, b: 0, id: 2}
Object {a: 1, b: 1, id: 3}
[0, 0] 和 [1, 0] 之间的边界似乎可以正常工作。但是 [0, 0] 和 [2, 0] 之间的边界没有!它还返回 [0, 1] 作为结果。为什么 [1, 0] 可以作为上限而 [2, 0] 不能?我觉得我要么犯了一个非常愚蠢的错误,要么从根本上误解了什么。
如果你错过了,here is the link to this on JS Bin again。
为 Josh 编辑:我最初只使用 bound(x,y) 进行了尝试,这与 bound(x,y,false,false) 相同。将其更改为bound(x,y,true,true) 可以看到here。输出是
[a, b] bound from [0, 0] to [1, 0]
[a, b] bound from [0, 0] to [2, 0]
Object {a: 1, b: 0, id: 2}
Object {a: 1, b: 1, id: 3}
对于这些东西的意义,我仍然没有很好的直观理解。
【问题讨论】:
标签: javascript indexeddb