//存儲數據
localStorage.setItem("name", "張三");
localStorage.setItem("age", "18");
//獲取數據
var name = localStorage.getItem("name");
var age = localStorage.getItem("age");
console.log(name);//輸出:張三
console.log(age);//輸出:18
三、sessionStorage
sessionStorage和localStorage十分類似,不同之處在于sessionStorage在關閉瀏覽器之后數據將被清空。和localStorage一樣,sessionStorage只能存儲字符串類型的值。//存儲數據
sessionStorage.setItem("name", "張三");
sessionStorage.setItem("age", "18");
//獲取數據
var name = sessionStorage.getItem("name");
var age = sessionStorage.getItem("age");
console.log(name);//輸出:張三
console.log(age);//輸出:18
四、IndexedDB
IndexedDB是一種非關系型數據庫,它使用key-value的方式存儲數據。它的優勢在于可以存儲更多類型的數據,并且支持異步操作。//打開數據庫
var request = indexedDB.open("MyDatabase", 1);
//創建對象倉庫
var db;
request.onupgradeneeded = function(event) {
db = event.target.result;
var objectStore = db.createObjectStore("MyObjectStore", { keyPath: "id" });
objectStore.createIndex("name", "name", { unique: false });
};
//添加數據
var transaction = db.transaction(["MyObjectStore"], "readwrite");
var objectStore = transaction.objectStore("MyObjectStore");
var request = objectStore.add({ id: 1, name: "張三", age: 18 });
request.onsuccess = function(event) {
console.log("數據添加成功");
};
//獲取數據
var transaction = db.transaction(["MyObjectStore"], "readonly");
var objectStore = transaction.objectStore("MyObjectStore");
var request = objectStore.get(1);
request.onsuccess = function(event) {
console.log("name:" + event.target.result.name + ", age:" + event.target.result.age);
};
以上是javascript中常用的數據庫及其應用,不同的數據庫有不同的優勢和適用場景。大家可以根據自己的需求來選擇適合的數據庫。