

新闻资讯
技术学院localStorage存取数据最安全做法是:存对象用JSON.stringify()、取值先判空再JSON.parse();键名用字母数字组合;超限时捕获QuotaExceededError并降级;避免clear()误删,批量删除需遍历判断前缀。
localStorage 只能存字符串,直接传对象或数字会自动调用 toString(),导致数据失真。比如存 {name: "张三", age: 25},不处理就存进去,取出来是 [object Object]。
实操建议:
JSON.stringify() 序列化false 变成 "")localStorage.setItem('user', JSON.stringify({name: "张三", age: 25}));
localStorage.setItem('count', String(100)); // 显式转字符串更可控
取出来的永远是字符串,哪怕你当初存的是数字或布尔值。不解析就直接用,很容易在条件判断或计算中出错——比如 if (localStorage.getItem('isLogin') === true) 永远为 false,因为取出来是 "true" 字符串。
常见错误现象:
JSON.parse(null) 报错:getItem() 找不到键时返回 null,不能直接丢给 JSON.parse()
动拼接字符串),JSON.parse() 会抛 SyntaxError
const userStr = localStorage.getItem('user');
const user = userStr ? JSON.parse(userStr) : null; // 先判空再解析
const count = Number(localStorage.getItem('count')) || 0;
removeItem(key) 删除单个键值对,clear() 清空全部。别在用户仅想“退出当前账号”时误用 clear(),可能把其他功能的配置(比如主题色、语言偏好)也删了。
使用注意点:
removeItem() 对不存在的键静默失败,不报错也不提示clear() 不可逆,且会影响同源下所有页面共享的 localStorage,谨慎用于生产环境Object.keys(localStorage) 判断前缀再删,比全清更稳妥// 安全地删一组以 'cart_' 开头的数据
Object.keys(localStorage).forEach(key => {
if (key.startsWith('cart_')) {
localStorage.removeItem(key);
}
});
多数浏览器限制在 5MB 左右(不是精确值,Chrome 是约 5.2MB,Safari 移动端可能只有 2.5MB),超限会触发 QuotaExceededError。但这个错误不会自动抛出——只有在 setItem() 失败时才发生,且部分旧版 Safari 还会静默截断。
关键应对方式:
new TextEncoder().encode(str).length(UTF-8 字节长度)比 str.length 更准null(需加短延时或重试)try {
localStorage.setItem('data', hugeString);
} catch (e) {
if (e.name === 'QuotaExceededError') {
console.warn('localStorage 空间不足');
// 触发清理逻辑或切换存储方案
}
}
实际项目里最容易被忽略的,是跨页面写入后立即读取的时机问题,以及未处理 null 就直接 JSON.parse() 的崩溃风险。