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 - 参考示例:待办事项通知(查看实时示例)。