IDBObjectStore: deleteIndex() 方法

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

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

请注意,此方法只能在 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①

浏览器兼容性

BCD 表格仅在浏览器中加载

另请参阅