IDBIndex: multiEntry 屬性

Baseline 已廣泛支援

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

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

IDBIndex 介面的只讀屬性 multiEntry 返回一個布林值,該值會影響當計算索引的鍵路徑得到一個數組時,索引的行為方式。

這在建立索引時使用 IDBObjectStore.createIndex 方法來決定。該方法接受一個可選的 options 引數,其 multiEntry 屬性被設定為 true/false

一個布林值。

影響
true 對於鍵陣列中的每個元素,在索引中都會有一條記錄。
false 對於每個是陣列的鍵,都有一條記錄。

示例

在以下示例中,我們打開了一個事務和一個物件儲存,然後從一個簡單的聯絡人資料庫中獲取了索引 lName。然後,我們使用 IDBIndex.openCursor 在該索引上打開了一個基本遊標——這與直接在 ObjectStore 上使用 IDBObjectStore.openCursor 開啟遊標的工作方式相同,但返回的記錄是根據索引排序的,而不是主鍵。

索引的多項入口狀態會記錄到控制檯:應返回 false

最後,我們遍歷每條記錄,並將資料插入 HTML 表中。有關完整的可執行示例,請參閱我們的 IndexedDB-examples demo 倉庫線上檢視示例)。

js
function displayDataByIndex() {
  tableEntry.textContent = "";
  const transaction = db.transaction(["contactsList"], "readonly");
  const objectStore = transaction.objectStore("contactsList");

  const myIndex = objectStore.index("lName");
  console.log(myIndex.multiEntry);

  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-idbindex-multientry

瀏覽器相容性

另見