关于localStorage和sessionStorage存储用法的一些细节说明----------localStorage和sessionStorage存储必须字符串化...
localStorage 和 sessionStorage 基本用法基本一致;localStorage需要會長時間保存,而sessionStorage會保存在當(dāng)前對話框,會隨著創(chuàng)庫的關(guān)閉而被清除,
存儲的數(shù)據(jù)格式必須是string;所以當(dāng)localStorage.setItem(a,b)時,不管b為何種數(shù)據(jù),在存儲時都會被強(qiáng)制轉(zhuǎn)化為string格式,進(jìn)而在拿取getItem(a)時得到的永遠(yuǎn)是字符串,
但是在存儲過程中如下細(xì)節(jié)需要注意:
1.存儲數(shù)組時如果不處理,得到的是數(shù)組元素的字符串,
如果想得到數(shù)組,必須先再存儲時將其字符串話
var arr=[1,2,3]; localStorage.setItem("temp",JSON.stringify(arr)); console.log(typeof localStorage.getItem("temp")); console.log(localStorage.getItem("temp")); //得到結(jié)果 string [1,2,3]此時雖然已經(jīng)得到數(shù)組,但是是字符串形式的數(shù)組,業(yè)務(wù)中需要將其JSON.parse(),轉(zhuǎn)換格式才能進(jìn)一步利用
var arr=[1,2,3]; localStorage.setItem("temp",JSON.stringify(arr)); console.log(typeof localStorage.getItem("temp")); console.log(localStorage.getItem("temp")); console.log(JSON.parse(localStorage.getItem("temp"))); //得到結(jié)果 string [1,2,3]//string [1, 2, 3]//array?
2.存儲對象(包括JSON對象)時如果不處理,得到的是對象元素的字符串,
var obj = {"a": 1,"b": 2}; localStorage.setItem("temp2", obj); console.log(typeof localStorage.getItem("temp2")); console.log(localStorage.getItem("temp2")); //得到結(jié)果 string [object Object]//鍵值對形式的字符串,因此是obj此時對于結(jié)果不管是用eval()還是JSON.parse(),都無法解析,如需業(yè)務(wù)中正常利用,必須在存儲前將其字符串化,然后獲取后再格式化
var obj={"a": 1,"b": 2}; localStorage.setItem("temp",JSON.stringify(obj)); console.log(typeof localStorage.getItem("temp")); console.log(localStorage.getItem("temp"));console.log(JSON.parse(localStorage.getItem("temp"))); console.log(typeof JSON.parse(localStorage.getItem("temp")));//得到結(jié)果 string {"a":1,"b":2}//string {a: 1, b: 2}//obj object?
總結(jié):正常業(yè)務(wù)中時,不管是數(shù)組還是JSON對象,為保證存儲讀取后能正常使用,最好存儲前JSON.stringify()一下需要存儲的數(shù)據(jù)
?
轉(zhuǎn)載于:https://www.cnblogs.com/yogic/p/9331019.html
總結(jié)
以上是生活随笔為你收集整理的关于localStorage和sessionStorage存储用法的一些细节说明----------localStorage和sessionStorage存储必须字符串化...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android acache读后感
- 下一篇: DOM事件处理有三个阶段