--- title: IDBIndex slug: Web/API/IDBIndex translation_of: Web/API/IDBIndex ---
{{APIRef()}}
IndexedDB API 中的IDBIndex接口提供了异步获取数据库中一个index的功能。index是一种用于在另一个object store中查找记录的object store,其被称为被引用的object store。你可以通过使用该接口来取回数据。
你可以通过记录的键或使用一个index取回一个object store中的这些记录 (cursors 提供了第三种方式:请见 {{ domxref("IDBCursor") }})。一个index可以让你在object store的records中,通过使用records的properties(属性)来寻找records。
index是一个持久的键-值存储,其中其记录的值部分是被引用object store中的record的关键部分。在object store中新增、更新或是删除records时,索引中的records将自动填充。索引中的每条记录只能指向其引用的object store中的唯一一条记录,但是多个索引可以引用同一个object store。当object store变更时,所有引用object store的索引都会自动更新。
索引中的records总是按照records的key进行排序。然而,不像object stores,一个给定的index可以包含具有相同key的多条记录。这些records将根据被引用object store中的主键进一步排序。
你可以设置在一个范围内的key,点击这里查看更多: {{domxref("IDBKeyRange")}}.
Inherits from: EventTarget
key
is a key range.result
of the request object.key
is a key range.result
of the request object.Opening a transaction then using get()
to retrieve an object of known key:
// Let us open our database var request = window.indexedDB.open("toDoList", 4); // these two event handlers act on the database being opened successfully, or not request.onerror = function(event) { note.innerHTML += '<li>Error loading database.</li>'; }; request.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variable. db = request.result; // Open a transaction on the current database and get a reference to the object store //that we want to pull information out of var transaction = db.transaction(["toDoList"]); var objectStore = transaction.objectStore("toDoList"); // Use get() to get a specific object from the object store, the key of which is "Walk dog" var request = objectStore.get("Walk dog"); request.onerror = function(event) { console.log("There is no record stored for " + request.result.taskTitle); }; request.onsuccess = function(event) { // Do something with the request.result! console.log("The deadline time for " + request.result.taskTitle + " is " + request.result.hours + ":" + request.result.minutes + "."; };
Note: need to work out a way to retrieve a series/range of objects using an index, or just all of them. Is this possible with get, or is this a job for cursor?
Specification | Status | Comment |
---|---|---|
{{SpecName('IndexedDB', '#idl-def-IDBIndex', 'IDBIndex')}} | {{Spec2('IndexedDB')}} |
To learn more about various topics, see the following