IDBObjectStore: autoIncrement 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

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

IDBObjectStore 介面的只讀屬性 autoIncrement 返回此物件儲存的自動遞增標誌的值。

請注意,每個物件儲存都有自己的獨立自動遞增計數器。

一個布林值。

含義
true 物件儲存自動遞增。
false 物件儲存不自動遞增。

示例

在下面的程式碼片段中,我們開啟資料庫的讀/寫事務,並使用 add() 向物件儲存中新增一些資料。建立物件儲存後,我們將 objectStore.autoIncrement 記錄到控制檯。有關完整的可執行示例,請參閱我們的 待辦事項通知 應用(線上檢視示例)。

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

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 = 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
  const 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
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of the transaction completing, when everything is done
  transaction.oncomplete = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction completed.";
  };

  transaction.onerror = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction not opened due to error. Duplicate items not allowed.";
  };

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

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

  objectStoreRequest.onsuccess = (event) => {
    // report the success of our request
    note.appendChild(document.createElement("li")).textContent =
      "Request successful.";
  };
}

規範

規範
Indexed Database API 3.0
# ref-for-dom-idbobjectstore-autoincrement①

瀏覽器相容性

另見