IDBObjectStore:deleteIndex() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

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

deleteIndex() 方法属于 IDBObjectStore 接口,用于在数据库连接期间销毁指定名称的索引,该方法用于版本升级过程中。

请注意,此方法只能从 VersionChange 事务模式的回调中调用。请注意,此方法会同步修改 IDBObjectStore.indexNames 属性。

语法

js
deleteIndex(indexName)

参数

indexName

要移除的现有索引的名称。

返回值

无(undefined)。

异常

InvalidStateError DOMException

如果方法不是从 versionchange 事务模式的回调中调用的,则会抛出此异常。

TransactionInactiveError DOMException

如果此 IDBObjectStore 所属的事务不是活动的(例如,已被删除或移除),则会抛出此异常。

NotFoundError DOMException

如果数据库中不存在具有给定名称(区分大小写)的索引,则会抛出此异常。

示例

在以下示例中,您可以看到 onupgradeneeded 处理程序用于在加载版本号更高的数据库时更新数据库结构。 IDBObjectStore.createIndex 用于在对象存储上创建新索引,之后我们使用 deleteIndex() 删除不再需要的旧索引。有关完整的可运行示例,请参阅我们的 待办事项通知 应用(在线查看示例)。

js
let db;

// Let us open our database
const DBOpenRequest = window.indexedDB.open("toDoList", 4);

// these two event handlers act on the database being opened successfully, or not
DBOpenRequest.onerror = (event) => {
  note.appendChild(document.createElement("li")).textContent =
    "Error loading database.";
};

DBOpenRequest.onsuccess = (event) => {
  note.appendChild(document.createElement("li")).textContent =
    "Database initialized.";

  // store the result of opening the database in the db variable. This is used a lot below
  db = event.target.result;

  // Run the displayData() function to populate the task list with all the to-do list data already in the IDB
  displayData();
};

// This event handles the event whereby a new version of the database needs to be created
// Either one has not been created before, or a new version number has been submitted via the
// window.indexedDB.open line above
// it is only implemented in recent browsers
DBOpenRequest.onupgradeneeded = (event) => {
  const db = event.target.result;

  db.onerror = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Error loading database.";
  };

  // Create an objectStore for this database
  const objectStore = db.createObjectStore("toDoList", {
    keyPath: "taskTitle",
  });

  // define what data items the objectStore will contain

  objectStore.createIndex("hours", "hours", { unique: false });
  objectStore.createIndex("minutes", "minutes", { unique: false });
  objectStore.createIndex("day", "day", { unique: false });
  objectStore.createIndex("month", "month", { unique: false });
  objectStore.createIndex("year", "year", { unique: false });
  objectStore.createIndex("notified", "notified", { unique: false });

  objectStore.deleteIndex("seconds");
  objectStore.deleteIndex("contact");
};

规范

规范
Indexed Database API 3.0
# ref-for-dom-idbobjectstore-deleteindex①

浏览器兼容性

另见