IDBIndex: name 屬性

Baseline 已廣泛支援

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

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

IDBIndex 介面的 name 屬性包含一個字串,該字串為索引命名。

指定索引名稱的字串。

異常

嘗試更改索引的名稱時,可能會發生幾種異常。

InvalidStateError DOMException

如果索引或其物件儲存已被刪除,或者當前事務不是升級事務,則會丟擲此異常。您只能在升級事務期間重新命名索引;也就是說,當模式為 "versionchange" 時。

TransactionInactiveError DOMException

如果當前事務未啟用,則會丟擲此異常。

ConstraintError DOMException

如果索引已在使用指定的 name,則會丟擲此異常。

示例

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

索引的名稱將記錄到控制檯:它應返回為 lName

最後,我們遍歷每個記錄,將資料插入 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.name);

  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
# ref-for-dom-idbindex-name①

瀏覽器相容性

另見