localStorage只能存字符串,直接存储对象会调用toString()变为"[object Object]";必须用JSON.stringify()序列化、JSON.parse()反序列化,并注意undefined、函数、Date等特殊类型的处理限制。
localStorage 只能存字符串,直接 setItem 一个对象会变成 [object Object],必须手动序列化。
localStorage 的底层 API 设计就是键值对字符串存储,所有非字符串值都会被隐式调用 toString()。比如:
localStorage.setItem('user', { name: 'Alice' });
console.log(localStorage.getItem('user')); // "[object Object]"
这不是 bug,是规范行为。所以必须显式转换为 JSON 字符串。
JSON.stringify() 是最常用且安全的序列化方式它能把大多数普通对象、数组、基础类型组合转成合法 JSON 字符串,且浏览器原生支持、无依赖、性能好。
null
undefined、函数、Date(会变 null)、RegExp、Symbol、循环引用JSON.stringify({ a: undefined, b: 1 }) → "{"b":1}")典型用法:
const user = { name: 'Alice', age: 28, isActive: true };
localStorage.setItem('user', JSON.stringify(user));
JSON.parse() 反序列化存进去的是字符串,取出来还是字符串,不 parse 就只是文本,不是对象。
JSON.parse() 是最常见错误,会导致后续调用 .name 报 TypeError: Cannot read property 'name' of null
try/catch,因为用户可能手动改过 localStorage,导致 JSON 格式损坏const userStr = localStorage.getItem('user');
let user = null;
try {
user = JSON.parse(userStr);
} catch (e) {
console.error('解析 localStorage 中的 user 失败', e);
}
JSON.stringify() 对 Date 默认只输出字符串(如 "2025-01-01T0),但反序列化后是字符串而非
0:00:00.000Z"Date 实例;Map/Set 则直接丢失。
Date 类型,可在 JSON.stringify() 第二个参数中处理:JSON.stringify(obj, (k, v) => v instanceof Date ? v.toISOString() : v)
new Date(str) 恢复(注意判断字段是否为 ISO 字符串)Array.from(map.entries())
没有银弹 —— 序列化方案永远取决于你存的是什么、读的时候要什么类型。别假设 JSON.stringify + JSON.parse 能覆盖全部场景。