localStorage
一句话解释
localStorage 是浏览器 API 那个存储键-值 pairs persistently on 客户端, surviving page reloads and 浏览器 restarts.
用大白话说
localStorage 是一种simple way to store data in the browser that persists even after the user closes the tab or browser。 It stores string key-value pairs and has no expiration — data stays until explicitly removed.
The API is straightforward: localStorage.setItem('键', '值') to store, localStorage.getItem('键') to retrieve, localStorage.removeItem('键') to delete, and localStorage.清晰() to remove everything. Values are always strings, so you must JSON.stringify objects and JSON.parse them back.
localStorage is synchronous, has a size limit (usually 5-10MB per origin), and is shared across all tabs on the same origin. It is great for user preferences, theme settings, and small amounts of cached data. Do not store sensitive data in it — any JavaScript on the page can read it.
示例
// Store user preference
localStorage.setItem("theme", "dark");
// Retrieve it
const theme = localStorage.getItem("theme"); // "dark"
// Store an object
localStorage.setItem("user", JSON.stringify({ name: "Ada" }));
const user = JSON.parse(localStorage.getItem("user")); // { name: "Ada" }存储 and retrieving 字符串 and 对象 in localStorage. 对象必须是 serialized 使用 JSON.
相关术语
相关资源
相关课程
- Web Storage
学习 web storage APIs.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。