IDBKeyRange: bound() 靜態方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

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

bound() 靜態方法是 IDBKeyRange 介面的一個方法,用於建立具有指定上限和下限的新鍵範圍。邊界可以是開放的(即,邊界不包含端點值)或閉合的(即,邊界包含端點值)。預設情況下,邊界是閉合的。

語法

js
IDBKeyRange.bound(lower, upper)
IDBKeyRange.bound(lower, upper, lowerOpen)
IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen)

引數

lower

指定新鍵範圍的下限。

upper

指定新鍵範圍的上限。

lowerOpen 可選

指示下限是否排除端點值。預設為 false。

upperOpen 可選

指示上限是否排除端點值。預設為 false。

返回值

IDBKeyRange: 新建立的鍵範圍。

異常

DataError DOMException

在滿足以下任一條件時丟擲

  • lower 或 upper 引數沒有傳遞有效鍵。
  • lower 鍵大於 upper 鍵。
  • lower 鍵和 upper 鍵匹配,並且任一邊界是開放的。

示例

以下示例說明了如何使用邊界鍵範圍。在此,我們宣告 keyRangeValue = IDBKeyRange.bound("A", "F"); — 一個介於 "A" 和 "F" 之間(包括 "A" 和 "F")的範圍。我們開啟一個事務(使用 IDBTransaction)和物件儲存,並使用 IDBObjectStore.openCursor 開啟一個遊標,將 keyRangeValue 宣告為其可選的鍵範圍值。這意味著遊標將只檢索該範圍內的記錄。此範圍包括 "A" 和 "F" 的值,因為我們沒有宣告它們應該是開放邊界。如果我們使用 IDBKeyRange.bound("A", "F", true, true);,那麼範圍將不包括 "A""F",而只包括它們之間的值。

注意: 有關更完整的示例,允許您嘗試鍵範圍,請檢視 indexeddb-examples 倉庫中的 idbkeyrange 目錄。(也可以 即時檢視示例

js
function displayData() {
  const keyRangeValue = IDBKeyRange.bound("A", "F");

  const transaction = db.transaction(["fThings"], "readonly");
  const objectStore = transaction.objectStore("fThings");

  objectStore.openCursor(keyRangeValue).onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.fThing}, ${cursor.value.fRating}`;
      list.appendChild(listItem);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}

規範

規範
Indexed Database API 3.0
# ref-for-dom-idbkeyrange-bound①

瀏覽器相容性

另見