iT邦幫忙

0

【30 天JavaScript 實戰 】 Day 14|本地儲存

  • 分享至 

  • xImage
  •  

在前幾天我們的表單與登入功能中,每次重新整理頁面資料都會消失。
今天我們要來解決這個問題,讓網站「記得」使用者的狀態~


今日的目標:

  • 了解Local Storage / Session Storage
  • 了解如何使用(setItem、getItem、removeItem)
  • 熟悉 JSON.stringify() / JSON.parse()

一、什麼是本地儲存(Local Storage / Session Storage)

瀏覽器提供兩種主要的前端儲存方式如下~

名稱 儲存期限 說明 常見用途
localStorage 永久儲存(除非手動刪掉或清除快取) 關掉瀏覽器也不會消失 登入狀態、顏色主題、購物車
sessionStorage 暫時儲存(關掉分頁就消失) 只存在當前頁面會話中 表單暫存資料、一次性登入頁面

二、如何使用?

存資料 setItem

localStorage.setItem("username", "高高");
sessionStorage.setItem("theme", "dark");

取資料 getItem

const user = localStorage.getItem("username");
console.log(user); // 高高 ( 如果沒有找到這個 key,會回傳 null

刪除或清空 removeItem / clear

localStorage.removeItem("username"); // 刪除單一項目
localStorage.clear(); // 清空全部

三、只能存字串?那物件怎麼辦?

瀏覽器儲存的值都會被「轉成字串」,
所以你不能直接放進一個物件,否則會變成這樣:

const user = { name: "高高", age: 18 };
localStorage.setItem("user", user); // ❌ [object Object]

這樣取出後根本不能用,所以我們要做「序列化」!

四、序列化:JSON.stringify() / JSON.parse()

// 1. 物件 → 字串
const user = { name: "高高", age: 18 };
localStorage.setItem("user", JSON.stringify(user));

// 2. 字串 → 物件
const savedUser = JSON.parse(localStorage.getItem("user"));
console.log(savedUser.name); // 高高

JSON.stringify() 會把 JS 物件轉成字串
JSON.parse() 再把字串轉回 JS 物件


/images/emoticon/emoticon35.gif


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言