S16-00 专题-JS-Storage
[TOC]
索引
基本属性
- Storage.length:
number
,只读,表示存储中键值对的总数。
基本方法
- Storage.getItem():
(key)
,返回key对应的value。 - Storage.setItem():
(key,value)
,将key和value添加到存储中。如果key存在则更新对应的值。 - Storage.removeItem():
(key)
,将该key从存储中删除。 - Storage.clear():
()
,清空存储中的所有key。 - Storage.key():
(index)
,根据索引获取存储对象中的指定键。
基础
认识Storage
WebStorage主要提供了一种机制,可以让浏览器提供一种比cookie更直观的key、value存储方式:
localStorage:本地存储,提供的是一种永久性的存储方法,在关闭掉网页重新打开时,存储的内容依然保留;
sessionStorage:会话存储,提供的是本次会话的存储,在关闭掉会话时,存储的内容会被清除;
对比localStorage、sessionStorage
我们会发现localStorage和sessionStorage看起来非常的相似。
那么它们有什么区别呢?
验证一:关闭网页后重新打开,localStorage会保留,而sessionStorage会被删除;
验证二:在页面内实现跳转,localStorage会保留,sessionStorage也会保留;
验证三:在页面外实现跳转(打开新的网页),localStorage会保留,sessionStorage不会被保留;
封装Cache
基础封装
优化:存储对象类型
原生方法
优化:兼容local和session
TypeScript
TS封装Cache@
使用TS封装的Cache类
enum EStorage {
Local,
Session
}
/** 封装Storage */
class Cache {
storage: Storage
constructor(type: EStorage) {
this.storage = type === EStorage.Local ? localStorage : sessionStorage
}
getItem(key: string) {
const res = this.storage.getItem(key)
return res ? JSON.parse(res) : ''
}
setItem(key: string, value: any) {
this.storage.setItem(key, JSON.stringify(value || ''))
}
removeItem(key: string) {
this.storage.removeItem(key)
}
clear() {
this.storage.clear()
}
key(index: number) {
return this.storage.key(index)
}
addItem(key: string, value: any) {
let res = this.getItem(key)
if (!res) {
// 不存在key
this.storage.setItem(key, JSON.stringify(value || ''))
} else {
// 存在key
if (Array.isArray(res)) {
res = Array.isArray(value) ? [...res, ...value] : [...res, value]
} else if (isObjectLiteral(res)) {
res = { ...res, ...value }
} else {
res += value + ''
}
this.storage.setItem(key, JSON.stringify(res))
}
}
}
export const localCache = new Cache(EStorage.Local)
export const sessionCache = new Cache(EStorage.Session)
工具方法
/**
* 判断是否为对象字面量
* @param value 要判断的值
* @returns {boolean} 是否为对象字面量
*/
function isObjectLiteral(value: any) {
return Object.prototype.toString.call(value) === '[object Object]' && value !== null && !Array.isArray(value)
}
测试
// 测试
localCache.setItem('age', 27)
// localCache.setItem('name', 'zhangsan')
// localCache.setItem('user', { name: 'zhangsan', age: 18 })
// localCache.setItem('count', ['one', 'two', 'three', 'four'])
// console.log(localCache.getItem('age'))
// console.log(localCache.getItem('name'))
// console.log(localCache.getItem('user'))
// console.log(localCache.getItem('count'))
// 添加值
// localCache.addItem('info', {})
// localCache.addItem('user', { city: 'beijing' })
// localCache.addItem('count', ['eight'])
// localCache.addItem('count', 'seven')
localCache.addItem('age', 10) // '2710'
API
基本属性
length
Storage.length:number
,只读,表示存储中键值对的总数。
返回:
length:
number
,返回当前存储对象中的键值对数量。- js
// 假设我们已经在 localStorage 中设置了一些键值对 localStorage.setItem('username', 'JohnDoe'); localStorage.setItem('age', '30'); localStorage.setItem('city', 'New York'); // 获取 localStorage 中的键值对数量 console.log(localStorage.length); // 输出: 3
基本方法
getItem()
Storage.getItem():(key)
,返回key对应的value。
key:
string
,存储项的标识符。返回:
value:
string | null
,返回与指定key相关联的值。不存在key则返回null。- js
// 存储一个对象 var userObj = { name: 'John Doe', age: 30 }; localStorage.setItem('user', JSON.stringify(userObj)); // 获取对象并解析 var userFromStorage = localStorage.getItem('user'); var parsedUser = JSON.parse(userFromStorage); console.log(parsedUser); // 输出: { name: 'John Doe', age: 30 }
setItem()
Storage.setItem():(key,value)
,将key和value添加到存储中。如果key存在则更新对应的值。
key:
string
,存储项的标识符。value:
string
,希望存储的数据。- js
// 存储一个字符串 localStorage.setItem('username', 'JohnDoe'); // 存储一个数字(数字会被自动转换为字符串) localStorage.setItem('age', 25); // 存储对象 var userObj = { name: 'John Doe', age: 30 }; localStorage.setItem('user', JSON.stringify(userObj)); // 存储数组 var arr = [1, 2, 3, 4]; localStorage.setItem('numbers', JSON.stringify(arr));
removeItem()
Storage.removeItem():(key)
,将该key从存储中删除。
key:
string
,要删除的存储项的键。不存在key则不会做任何事。- js
// 假设当前没有 'email' 键的存储项 localStorage.removeItem('email'); // 不会做任何事情,也不会抛出错误
clear()
Storage.clear():()
,清空存储中的所有key。
- js
// 假设存储了多个键值对 localStorage.setItem('username', 'JohnDoe'); localStorage.setItem('age', '30'); // 清空所有存储项 localStorage.clear(); // 尝试获取任何键的数据,都会返回 null console.log(localStorage.getItem('username')); // 输出: null console.log(localStorage.getItem('age')); // 输出: null
key()
Storage.key():(index)
,根据索引获取存储对象中的指定键。
index:
number
,要获取的存储项的索引位置。从0开始。返回:
key:
string | null
,返回的是存储对象中指定位置的键名。如果超出范围返回null。- js
// 假设存储了多个键值对 localStorage.setItem('username', 'JohnDoe'); localStorage.setItem('age', '30'); localStorage.setItem('city', 'New York'); // 遍历所有存储项的键名 for (let i = 0; i < localStorage.length; i++) { console.log(localStorage.key(i)); // 输出每个存储项的键名 }