大网数据广告活动
Web 标准与前端开发

IDBObjectStore.autoIncrement

· 52CE 我爱测

IDBObjectStore的只读属性 **`autoIncrement`** 接口返回当前 objectStore 的自增标记值(true 或 false)。

IndexedDB

IDBObjectStore的只读属性 autoIncrement 接口返回当前 objectStore 的自增标记值(true 或 false)。

什么是自增呢?熟悉 SQL 的朋友应该知道,SQL 数据里面的字段可以设置自增,当一条记录被插入时,不必传入该字段,新记录的该字段值会在前面一条记录该字段值的基础上加 1.而 indexedDB 里面的 autoIncrement 的同样的意义。(译者注)

注意:每个 objectStore 的 auto increment 计数器是分开独立的。

值

Boolean:

值 含义
true 当前 objectStore 会自增
false 当前 objectStore 不会自增

示例

在下面代码片段中,我们在数据库里打开了一个可读写的事务(transaction),并且用add()向一个 objectStore 中添加了一些数据。在 objectStore 被创建之后,我们在 console 中打印了 objectStore.autoIncrement 的值。想查看完整的例子,请查看我们的To-do Notifications应用(查看在线例子)。

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

DBOpenRequest.onsuccess = function (event) {
  note.innerHTML += "<li>Database initialised.</li>";

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

  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready to insert into the IDB
  var newItem = [
    {
      taskTitle: "Walk dog",
      hours: 19,
      minutes: 30,
      day: 24,
      month: "December",
      year: 2013,
      notified: "no",
    },
  ];

  // open a read/write db transaction, ready for adding the data
  var transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = function (event) {
    note.innerHTML += "<li>Transaction completed.</li>";
  };

  transaction.onerror = function (event) {
    note.innerHTML +=
      "<li>Transaction not opened due to error. Duplicate items not allowed.</li>";
  };

  // create an object store on the transaction
  var objectStore = transaction.objectStore("toDoList");
  console.log(objectStore.autoIncrement);

  // Make a request to add our newItem object to the object store
  var objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = function (event) {
    // report the success of our request
    note.innerHTML += "<li>Request successful.</li>";
  };
}

规范

浏览器兼容性

参见

  • 使用 IndexedDB
  • 开始学习事务 transactions: IDBDatabase
  • 使用事务 transactions: IDBTransaction
  • key 值域 range 的使用:IDBKeyRange
  • 检索、修改:IDBObjectStore
  • 使用游标:IDBCursor
  • 相关例子:To-do Notifications (view example live.)

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。