IDBObjectStore: index() 方法
注意:此功能在 Web Workers 中可用。
IDBObjectStore 介面的 index() 方法會在當前物件儲存中開啟一個命名索引,之後可以使用該索引,例如,透過遊標返回一系列按該索引排序的記錄。
語法
js
index(name)
引數
name-
要開啟的索引的名稱。
返回值
一個用於訪問索引的 IDBIndex 物件。
異常
InvalidStateErrorDOMException-
如果源物件儲存已被刪除,或者物件儲存的事務已完成,則丟擲此錯誤。
NotFoundErrorDOMException-
如果資料庫中不存在指定名稱(區分大小寫)的索引,則丟擲此錯誤。
示例
在以下示例中,我們打開了一個事務和一個物件儲存,然後從一個簡單的聯絡人資料庫中獲取了索引 lName。然後,我們使用 IDBIndex.openCursor 在該索引上打開了一個基本遊標——這與直接在 ObjectStore 上使用 IDBObjectStore.openCursor 開啟遊標的工作方式相同,但返回的記錄是根據索引排序的,而不是主鍵。
最後,我們遍歷每條記錄,並將資料插入 HTML 表格。有關完整的可執行示例,請參閱我們的 IndexedDB 示例儲存庫中的 IDBIndex 示例(立即檢視示例)。
js
function displayDataByIndex() {
tableEntry.textContent = "";
const transaction = db.transaction(["contactsList"], "readonly");
const objectStore = transaction.objectStore("contactsList");
const myIndex = objectStore.index("lName");
myIndex.openCursor().onsuccess = (event) => {
const cursor = event.target.result;
if (cursor) {
const tableRow = document.createElement("tr");
for (const cell of [
cursor.value.id,
cursor.value.lName,
cursor.value.fName,
cursor.value.jTitle,
cursor.value.company,
cursor.value.eMail,
cursor.value.phone,
cursor.value.age,
]) {
const tableCell = document.createElement("td");
tableCell.textContent = cell;
tableRow.appendChild(tableCell);
}
tableEntry.appendChild(tableRow);
cursor.continue();
} else {
console.log("Entries all displayed.");
}
};
}
規範
| 規範 |
|---|
| Indexed Database API 3.0 # dom-idbobjectstore-index |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。