日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

关于localStorage和sessionStorage存储用法的一些细节说明----------localStorage和sessionStorage存储必须字符串化...

發布時間:2023/12/18 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 关于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",arr); console.log(typeof localStorage.getItem("temp")); console.log(localStorage.getItem("temp"));//得到結果 string;1,2,3;

如果想得到數組,必須先再存儲時將其字符串話

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存储必须字符串化...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。