清空localStorage (clear
)
localStorage.clear();//清空本地緩存
存儲數(shù)據(jù) (setItem
)
localStorage.setItem('key',value);
//或者是localStorage.key=value; value類型必須是字符串類型蜡坊!
localStorage //Storage {key: value, length: 1}
讀取數(shù)據(jù) (getItem
)
localStorage.getItem('key');//根據(jù)參數(shù)key取得本地緩存中對應的值
localStorage.valueOf()//讀取所有數(shù)據(jù)
localStorage.key(0) //讀取第一條數(shù)據(jù)(key-value)
刪除某個變量 (removeItem
)
localStorage.removeItem('key');//刪除key所對應的那一條本地緩存
是否存在某個變量 (hasOwnProperty)
localStorage.hasOwnProperty('age'); // 判斷當前LocalStorage是否有"age"這條記錄(不包括原型屬性)
//hasOwnProperty() 只能判斷屬性是否存在實例對象中不能判斷是否存在原型對象中
將JSON存儲在localStorage
localStorage中只能存儲字符串漱受,所以我們經(jīng)常會用到
JSON.stringify(Object)將一個對象轉(zhuǎn)換為字符串
再使用JSON.parse(ObjString)將一個字符串轉(zhuǎn)換為對象
let hero ={
Assassin:{
name:"劫",
age:22
},
Master:{
name:"光輝",
age:18
}
}
//將JSON存儲在localStorage步驟
//首先要將JSON轉(zhuǎn)化為字符串到一個變量 (JSON.stringify())
//將這個變量存儲在localStorage上
//最后獲取的時候再轉(zhuǎn)化為JSON (JSON.parse())
hero = JSON.stringify(hero); //將hero轉(zhuǎn)化成字符串
localStorage.setItem("hero",hero);//localStorage只能存儲字符串hero必須是字符串類型
let newHero = localStorage.getItem('hero');//獲取hero內(nèi)容
newHero = JSON.parse(hero);//將hero轉(zhuǎn)化為JSON命名為新的變量newHero
window.onbeforeunload
當窗口關閉的時候發(fā)生的事件
window.onbeforeunload = function(){
// 高版本需要按F5刷新一下
return "拜拜~";
}