- IndexedDB 教程
- IndexedDB - 首頁
- IndexedDB - 簡介
- IndexedDB - 安裝
- IndexedDB - 連線
- IndexedDB - 物件儲存
- IndexedDB - 建立資料
- IndexedDB - 讀取資料
- IndexedDB - 更新資料
- IndexedDB - 刪除資料
- 使用 getAll() 函式
- IndexedDB - 索引
- IndexedDB - 範圍
- IndexedDB - 事務
- IndexedDB - 錯誤處理
- IndexedDB - 搜尋
- IndexedDB - 遊標
- IndexedDB - Promise 包裝器
- IndexedDB - Ecmascript 繫結
- IndexedDB 有用資源
- IndexedDB - 快速指南
- IndexedDB - 有用資源
- IndexedDB - 討論
IndexedDB - 索引
索引是一種物件儲存,用於透過指定的屬性儲存的參考物件中提取資料。即使索引位於參考物件儲存中幷包含相同的資料,但它使用指定屬性作為其關鍵路徑,而不是參考儲存的主鍵。
索引用於定義資料上的唯一約束,並且在建立物件儲存時進行建立。要建立索引,請在物件儲存例項上呼叫 createIndex 方法 -
語法
var myIDBIndex = objectStore.createIndex(indexName, keyPath); var myIDBIndex = objectStore.createIndex(indexName, keyPath, objectParameters);
此方法建立一個並返回一個索引物件。該方法建立了一個採用以下引數的索引 -
索引名稱 - 索引的名稱。
鍵路徑 - 我們在此處提到主鍵。
物件引數 - 有兩個物件引數。
唯一 - 無法新增重複值。
多條目 - 如果 true,則當 keyPath 解析為陣列時,該索引將在索引中新增每個陣列元素的條目。如果 false,它將新增一個包含該陣列的單個條目。
示例
以下示例顯示了物件儲存中索引的實現 -
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
const request = indexedDB.open("botdatabase",1);
request.onupgradeneeded = function(){
const db = request.result;
const store = db.createObjectStore("bots",{ keyPath: "id"});
store.createIndex("branch_db",["branch"],{unique: false});
}
request.onsuccess = function(){
document.write("database opened successfully");
const db = request.result;
const transaction=db.transaction("bots","readwrite");
const store = transaction.objectStore("bots");
const branchIndex = store.index("branch_db");
store.add({id: 1, name: "jason",branch: "IT"});
store.add({id: 2, name: "praneeth",branch: "CSE"});
store.add({id: 3, name: "palli",branch: "EEE"});
store.add({id: 4, name: "abdul",branch: "IT"});
store.put({id: 4, name: "deevana",branch: "CSE"});
transaction.oncomplete = function(){
db.close;
}
}
</script>
</body>
</html>
輸出
branchIndex:
1
['CSE']
0: "CSE"
length: 1
4
{id: 4, name: 'deevana', branch: 'CSE'}
branch: "CSE"
id: 4
name: "deevana"
2
['EEE']
0: "EEE"
length: 1
3
{id: 3, name: 'palli', branch: 'EEE'}
branch: "EEE"
id: 3
name: "palli"
3
['IT']
0: "IT"
length: 1
1
{id: 1, name: 'jason', branch: 'IT'}
branch: "IT"
id: 1
name: "jason"
廣告