Storing arrays and objects using Sessionstorage, Localstorage

Source: Internet
Author: User
Tags sessionstorage

Sometimes, we need to store data in Sessionstorage and Localstorage, and the benefits are:

1 Cached data

2 Reduce memory footprint

However, storage can only store string data, but cannot be stored directly for arrays or objects that are commonly used in JS.

var obj = {name: ' Jim '};
Sessionstorage.obj = obj; 
Localstorage.obj = obj; 

var arr = [1,2,3]; 
Sessionstorage.obj = arr; 
Localstorage.obj = arr;



The above wording is not successful. But we can use the parse and stringify provided by the JSON object to convert the other data types into strings and then store them in the storage. Take a look at the code below.


var obj = {name: ' Jim '}; 
var str = json.stringify (obj); 

deposited 
sessionstorage.obj = str; 
Read 
str = sessionstorage.obj; 
Re-convert to object 
obj = Json.parse (str);


Localstorage, too, is just different from sessionstorage storage time.

It should be noted that the array in JS is also an object type, so the above code is also applicable to the arrays.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.