IDBObjectStore: getKey() 方法
注意:此功能在 Web Workers 中可用。
IDBObjectStore 介面的 getKey() 方法返回一個 IDBRequest 物件,並在單獨的執行緒中返回由指定查詢選擇的鍵。此方法用於從物件儲存中檢索特定記錄。
如果成功找到鍵,則會建立該鍵的結構化克隆並將其設定為請求物件的結果。
語法
js
getKey(key)
引數
key-
用於標識要檢索的記錄的鍵或鍵範圍。
返回值
一個 IDBRequest 物件,後續與此操作相關的事件會在此物件上觸發。
如果操作成功,請求的 result 屬性的值將是第一個匹配給定鍵或鍵範圍的記錄的鍵。
異常
此方法可能會丟擲以下型別之一的DOMException:
InvalidStateErrorDOMException-
如果
IDBObjectStore已被刪除或移除,則會丟擲此異常。 TransactionInactiveErrorDOMException-
如果此
IDBObjectStore的事務不活躍,則會丟擲此異常。 DataErrorDOMException-
如果提供的鍵或鍵範圍包含無效鍵,則會丟擲此異常。
示例
js
let openRequest = indexedDB.open("telemetry");
openRequest.onsuccess = (event) => {
let db = event.target.result;
let store = db.transaction("net-logs").objectStore("net-logs");
let today = new Date();
let yesterday = new Date(today);
yesterday.setDate(today.getDate() - 1);
let request = store.getKey(IDBKeyRange(yesterday, today));
request.onsuccess = (event) => {
let when = event.target.result;
alert(`The 1st activity in last 24 hours was occurred at ${when}`);
};
};
規範
| 規範 |
|---|
| Indexed Database API 3.0 # ref-for-dom-idbobjectstore-getkey① |
瀏覽器相容性
載入中…
另見
- 使用 IndexedDB
- 開始事務:
IDBDatabase - 使用事務:
IDBTransaction - 設定鍵的範圍:
IDBKeyRange - 檢索和修改資料:
IDBObjectStore - 使用遊標:
IDBCursor - 參考示例:待辦事項通知(檢視即時示例)。