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