WebStorage(js 本地存储)
存储内容大小一般支持 5MB 左右(不同浏览器可能还不一样)
浏览器端通过Window.sessionStorage和Window.localStorage属性来实现本地存储机制
相关API
xxxStorage.setItem('key', 'value')
: 该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值
xxxStorage.getItem('key')
: 该方法接受一个键名作为参数,返回键名对应的值
xxxStorage.removeItem('key')
: 该方法接受一个键名作为参数,并把该键名从存储中删除
xxxStorage.clear()
: 该方法会清空存储中的所有数据
备注
SessionStorage存储的内容会随着浏览器窗口关闭而消失
LocalStorage存储的内容,需要手动清除才会消失
xxxStorage.getItem(xxx)如果 xxx 对应的 value 获取不到,那么getItem()的返回值是null
JSON.parse(null)的结果依然是null
localStorage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <h2>localStorage</h2> <button onclick="saveDate()">点我保存数据</button><br/> <button onclick="readDate()">点我读数据</button><br/> <button onclick="deleteDate()">点我删除数据</button><br/> <button onclick="deleteAllDate()">点我清空数据</button><br/>
<script> let person = {name:"JOJO",age:20} function saveDate(){ localStorage.setItem('msg','localStorage') localStorage.setItem('person',JSON.stringify(person)) } function readDate(){ console.log(localStorage.getItem('msg')) const person = localStorage.getItem('person') console.log(JSON.parse(person)) } function deleteDate(){ localStorage.removeItem('msg') localStorage.removeItem('person') } function deleteAllDate(){ localStorage.clear() } </script>
|
sessionStorage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <h2>sessionStorage</h2> <button onclick="saveDate()">点我保存数据</button><br/> <button onclick="readDate()">点我读数据</button><br/> <button onclick="deleteDate()">点我删除数据</button><br/> <button onclick="deleteAllDate()">点我清空数据</button><br/>
<script> let person = {name:"JOJO",age:20} function saveDate(){ sessionStorage.setItem('msg','sessionStorage') sessionStorage.setItem('person',JSON.stringify(person)) } function readDate(){ console.log(sessionStorage.getItem('msg')) const person = sessionStorage.getItem('person') console.log(JSON.parse(person)) }
function deleteDate(){ sessionStorage.removeItem('msg') sessionStorage.removeItem('person') }
function deleteAllDate(){ sessionStorage.clear() } </script>
|