IDBObjectStore.clear()

admin發表於2019-09-18

clear()方法可以清除IndexedDB資料庫指定物件倉庫中的所有記錄。

此方法是一個非同步操作,返回IDBRequest型別物件,通過相關事件獲取操作狀態。

關於indexedDB資料非同步操作介紹可以參閱IndexedDB 非同步API概述一章節。

語法結構:

[JavaScript] 純文字檢視 複製程式碼
let request = objectStore.clear();

此方法是一次性清空物件倉庫中所有記錄,如果要刪除指定記錄,請使用IDBObjectStore.delete()方法。

關於上述方法的具體用法可以參閱IDBObjectStore.delete()一章節。

程式碼例項:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
let students=[
  { 
    id:1001, 
    name:"張三", 
    age:21,
    sex:"男"
  },{ 
    id:1002, 
    name:"李四", 
    age:20,
    sex:"女"
  },{ 
    id:1003, 
    name:"王五", 
    age:19,
    sex:"女"
  }
];
let request = window.indexedDB.open("antzone", 1);
request.onupgradeneeded = (ev) => {
  let db = ev.target.result;
  if (!db.objectStoreNames.contains('students')) {
    let objectStore = db.createObjectStore('students',{autoIncrement:true});
    objectStore.createIndex("xingbie","sex",{ unique: false });
}
}
request.onsuccess = (ev) => {
  let db = ev.target.result;
  let transaction = db.transaction(['students'], 'readwrite');
  let objectStore = transaction.objectStore('students');
  for(let i=0;i<students.length;i++){
    objectStore.add(students[i]);
  }
}
</script>
</head>
<body>
  <p>為物件倉庫批量新增資料</p>
</body>
</html>

上述程式碼為物件倉庫批量新增三條記錄,程式碼執行效果截圖如下:

a:3:{s:3:\"pic\";s:43:\"portal/201909/18/225449y3i0yytfsst3iwwc.jpg\";s:5:\"thumb\";s:0:\"\";s:6:\"remote\";N;}

下面通過clear()方法將物件倉庫中的記錄全部清空。

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script>
let students=[
  { 
    id:1001, 
    name:"張三", 
    age:21,
    sex:"男"
  },{ 
    id:1002, 
    name:"李四", 
    age:20,
    sex:"女"
  },{ 
    id:1003, 
    name:"王五", 
    age:19,
    sex:"女"
  }
];
let request = window.indexedDB.open("antzone", 1);
request.onupgradeneeded = (ev) => {
  let db = ev.target.result;
  if (!db.objectStoreNames.contains('students')) {
    let objectStore = db.createObjectStore('students',{autoIncrement:true});
    objectStore.createIndex("xingbie","sex",{ unique: false });
}
}
request.onsuccess = (ev) => {
  let db = ev.target.result;
  let transaction = db.transaction(['students'], 'readwrite');
  let objectStore = transaction.objectStore('students');
  for(let i=0;i<students.length;i++){
    objectStore.add(students[i]);
  }
  objectStore.clear();
}
</script>
</head>
<body>
  <p>清空物件倉庫</p>
</body>
</html>

在JavaScript程式碼的尾部新增objectStore.clear(),即可將物件倉庫清空。