http://my.oschina.net/crazymus/blog/371757 using Sessionstorage, Localstorage storage arrays and objects posted 3 month ago (2015-01-26 12:11) Read (708) | Comments (0) 5 People collection This article, I want to collect likes 0
Mu-NET, programmer promotion raise pay artifact, click Free to learn
Mobile Web
Sometimes we need to store the data in Sessionstorage and Localstorage, and the benefits are:
1 Caching data
2 Reduction in memory footprint
However, storage can only store strings of data, for the usual array or object in JS can not be stored directly.
?
1234567 |
var obj = { name: ‘Jim‘ }; sessionStorage.obj = obj; localStorage.obj = obj; var arr = [1,2,3]; sessionStorage.obj = arr; localStorage.obj = arr; |
The above is not a successful formulation! But we can convert other data types into strings through the parse and stringify provided by the JSON object, and then store them in storage. Take a look at the following code.
?
123456789 |
var obj = { name: ‘Jim‘ }; var str = JSON.stringify(obj); //存入 sessionStorage.obj = str; //读取 str = sessionStorage.obj; //重新转换为对象 obj = JSON.parse(str); |
Localstorage is the same, but the storage time is not the same as sessionstorage.
It is important to note that the array in JS is essentially an object type, so the above code is also applicable to arrays.
Storing arrays and objects using Sessionstorage, Localstorage (GO)