localStorage是浏览器持久化本地存储机制,仅支持字符串、跨页面共享且关浏览器不丢失;需用JSON序列化存对象,与sessionStorage区别在于生命周期和作用域。
localStorage 是浏览器内置的持久化本地存储机制,用起来简单,但几个关键点必须清楚:它只认字符串,跨页面共享,关浏览器也不丢数据。
所有操作都通过 setItem、getItem、removeItem 和 clear 四个方法完成:
localStorage.setItem("theme", "dark") —— 键和值都必须是字符串const theme = localStorage.getItem("theme") —— 不存在时返回 null,不是 undefined
:localStorage.removeItem("theme")
localStorage.clear()
存对象或数组时要手动序列化:localStorage.setItem("user", JSON.stringify({name: "小明", age: 28}))
读取时再解析:const user = JSON.parse(localStorage.getItem("user"))
两者 API 完全一致,差异集中在生命周期和作用域:
选错容易引发逻辑 bug 或体验问题:
实际开发中容易忽略的细节:
[object Object],取出来无法使用if (typeof localStorage !== 'undefined') 防御