打開開發者工具(右鍵 → 檢視) 點application,左邊就可以看到local storage、session storage 資訊
localStorage.setItem('userName', 'John');
到開發者工具,application的local storage會看到剛新增的一筆資料
console.log(localStorage.getItem('userName'));
localStorage['userName'] = "Jay";
var name = localStorage['userName']
localStorage.userName = "Jay";
var name = localStorage.userName
localStorage.setItem('userName', 'John');
localStorage.setItem('age', '29');
localStorage.setItem('city', 'taipei');
//刪除年齡
console.log(localStorage.removeItem('age'));
想刪除全部的資料
localStorage.setItem('userName', 'John');
localStorage.setItem('age', '29');
localStorage.setItem('city', 'taipei');
//一次清除上面三筆
localStorage.clear();
value只能是字串,因此如果小要儲存json資料,可用 JSON.stringify() 存入 用 JSON.parse() 取回
var obj = [
{
name: "John",
age: 29
}
]
var jsonString = JSON.stringify(obj);
console.log(typeof(jsonString)); //string
var obj = [
{
name: "John",
age: 29
}
]
var jsonString = JSON.stringify(obj);
var jsonObj = JSON.parse(jsonString);
console.log(typeof(jsonObj)); //object
console.log(obj[0].name); //John
var userInfo = [
{name: 'John',
city: 'Taipei'
}
];
//將陣列資料變成字串
var userInfoString = JSON.stringify(userInfo);
console.log(userInfoString);
//儲存
localStorage.setItem('user',userInfoString);
//獲取資料
var getData = localStorage.getItem('user');
console.log(typeof(getData)); //string
//將字串資料轉為陣列
var getDataAry = JSON.parse(getData);
console.log(typeof(getDataAry)); //object
//可以撈出第0筆的name資料
console.log(getDataAry[0].name); //John