更簡單的處理儲存方式
localStorage
,sessionStorage
是 JavaScript 物件,你可以這樣對待它們。
而不是像 .getItem()
,.setItem()
等使用儲存方法……這裡有一個更簡單的選擇:
// Set
localStorage.greet = "Hi!"; // Same as: window.localStorage.setItem("greet", "Hi!");
// Get
localStorage.greet; // Same as: window.localStorage.getItem("greet");
// Remove item
delete localStorage.greet; // Same as: window.localStorage.removeItem("greet");
// Clear storage
localStorage.clear();
例:
// Store values (Strings, Numbers)
localStorage.hello = "Hello";
localStorage.year = 2017;
// Store complex data (Objects, Arrays)
var user = {name:"John", surname:"Doe", books:["A","B"]};
localStorage.user = JSON.stringify( user );
// Important: Numbers are stored as String
console.log( typeof localStorage.year ); // String
// Retrieve values
var someYear = localStorage.year; // "2017"
// Retrieve complex data
var userData = JSON.parse( localStorage.user );
var userName = userData.name; // "John"
// Remove specific data
delete localStorage.year;
// Clear (delete) all stored data
localStorage.clear();