localStorage只存储字符串,存对象需JSON.stringify()、取时需JSON.parse()并加try...catch;数字布尔值会丢失类型,需手动转换;键名建议用字母数字下划线;不同源数据不共享,容量5–10MB,敏感信息勿存。
localStorage 存取数据很简单,但关键在细节:它只认字符串,存对象或数字必须手动转换,取出来也得还原,否则会出错。
用 setItem(key, value) 方法,两个参数都必须是字符串:
localStorage.setItem('theme', 'dark')
localStorage.setItem('count', 42) 实际存的是 '42',取出来是字符串不是数字JSON.stringify():localStorage.setItem('user', JSON.stringify({name: '李四', age: 30}))
用 getItem(key),返回的是字符串,要还原成原始类型:
const theme = localStorage.getItem('theme')
const count = Number(localStorage.getItem('count')) 或 const active = localStorage.getItem('active') === 'true'
JSON.parse(),且强烈建议加 try...catch 防止解析失败:try {<br> const user = JSON.parse(localStorage.getItem('user'));<br>} catch (e) {<br> // 数据损坏或为空时兜底处理<br>}
有两种常用方式:
立即学习“Java免费学习笔记(深入)”;
localStorage.removeItem('theme')
localStorage.clear() —— 慎用,会删除当前域名下所有 localStorage 数据实际开发中容易踩坑的地方:
QuotaExceededError 异常