localStorage只存储字符串,存对象需JSON.stringify(),读取需判空并JSON.parse();作用域按origin隔离;clear()是危险操作,应优先使用removeItem()。
localStorage 不是“存进去就能用”,它只认字符串,存对象不序列化就等于白存,读出来不判空不解析就必然报错。
直接 localStorage.setItem('user', {name: 'Alice'}) 看似没报错,实际存进去的是 "[object Object]" —— 后续 JSON.parse() 会直接抛 SyntaxError。
localStorage.setItem('user', JSON.stringify({name: 'Alice', age: 28}))
Date、RegExp、函数、undefined 无法被 JSON.stringify() 正常处理,比如 new Date() 要先转成 toISOString()
{a: {}}; a.b = a)会触发 TypeError: Converting circular structure to JSON,需提前剥离或用自定义 replacergetItem() 找不到键时返回 null,不是 undefined,也不是空字符串。直接 JSON.parse(null) 会炸。
const userStr = localStorage.getItem('user'); const user = userStr ? JSON.parse(userStr) : null;
try...catch,因为用户可能手动篡改过值,导致 JSON 格式损坏getItem() 都是 null
它按完整 origin(协议 + 域名 + 端口)隔离。这意味着:
立即学习“前端免费学习笔记(深入)”;
http://localhost:3000 和 http://localhost:3001 是两个完全独立的存储空间https://example.com 和 http://example.com 互不可见file:/// 协议,Chrome、Edge 等现代浏览器默认禁用 localStorage,会直接抛 SecurityError
python3 -m http.server 8000 或 Vite / Webpack Dev ServerlocalStorage.clear() 是“核按钮”:它删当前 origin 下所有键,不可逆,且不会通知其他标签页做了什么。
localStorage.clear(),除非是明确的用户主动“重置所有设置”操作localStorage.removeItem('theme') 或批量移除:['cart', 'searchHistory'].forEach(k => localStorage.removeItem(k))
Object.keys(localStorage).filter(k => !['token', 'userId'].includes(k)).forEach(k => localStorage.removeItem(k))
真正容易被忽略的不是语法,而是边界:用户在无痕模式下可能根本没开 storage;5MB 限制不是按字符数算,中文、emoji、Base64 都吃得多;storage 事件不会在当前页触发——这些细节不提前踩一遍,上线后问题都是静默发生的。