IDBObjectStore: getKey() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

注意:此功能在 Web Workers 中可用。

IDBObjectStore 介面的 getKey() 方法返回一個 IDBRequest 物件,並在單獨的執行緒中返回由指定查詢選擇的鍵。此方法用於從物件儲存中檢索特定記錄。

如果成功找到鍵,則會建立該鍵的結構化克隆並將其設定為請求物件的結果。

語法

js
getKey(key)

引數

key

用於標識要檢索的記錄的鍵或鍵範圍。

返回值

一個 IDBRequest 物件,後續與此操作相關的事件會在此物件上觸發。

如果操作成功,請求的 result 屬性的值將是第一個匹配給定鍵或鍵範圍的記錄的鍵。

異常

此方法可能會丟擲以下型別之一的DOMException

InvalidStateError DOMException

如果 IDBObjectStore 已被刪除或移除,則會丟擲此異常。

TransactionInactiveError DOMException

如果此 IDBObjectStore 的事務不活躍,則會丟擲此異常。

DataError DOMException

如果提供的鍵或鍵範圍包含無效鍵,則會丟擲此異常。

示例

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①

瀏覽器相容性

另見