js实现storage
使用 localStorage 实现数据存储
localStorage 是浏览器提供的持久化存储方案,适合存储键值对形式的数据,关闭浏览器后数据仍保留。
// 存储数据
localStorage.setItem('key', 'value');
// 读取数据
const value = localStorage.getItem('key');
// 删除指定数据
localStorage.removeItem('key');
// 清空所有数据
localStorage.clear();
使用 sessionStorage 实现会话存储
sessionStorage 与 localStorage 类似,但数据仅在当前会话有效,关闭浏览器标签页后数据自动清除。

// 存储数据
sessionStorage.setItem('sessionKey', 'sessionValue');
// 读取数据
const sessionValue = sessionStorage.getItem('sessionKey');
使用 IndexedDB 实现复杂数据存储
对于需要存储大量结构化数据的场景,IndexedDB 提供了更强大的解决方案。

// 打开或创建数据库
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const store = db.createObjectStore('myStore', { keyPath: 'id' });
};
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction('myStore', 'readwrite');
const store = transaction.objectStore('myStore');
// 添加数据
store.add({ id: 1, name: 'Item 1' });
// 获取数据
const getRequest = store.get(1);
getRequest.onsuccess = () => {
console.log(getRequest.result);
};
};
使用 Cookies 实现小数据存储
Cookies 适合存储少量数据,每次HTTP请求都会自动发送到服务器。
// 设置cookie
document.cookie = 'username=John; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/';
// 读取cookie
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
使用现代浏览器 Cache API
Cache API 允许对请求/响应对象进行缓存,适合存储网络资源。
// 打开缓存
caches.open('my-cache').then(cache => {
// 添加资源到缓存
cache.add('/api/data');
// 匹配缓存中的资源
cache.match('/api/data').then(response => {
if (response) {
console.log('Found in cache');
}
});
});
注意事项
- localStorage 和 sessionStorage 有存储限制(通常5MB)
- 敏感数据不应存储在客户端
- IndexedDB 操作是异步的,需要处理回调或使用 Promise
- 跨域情况下 cookie 访问受限
- 清除浏览器数据会删除所有存储内容






