How to store and read data using localStorage in Javascript?

When we develop website applications, we may need to store and read some data for a long time, but it is quite cumbersome to save it to the machine in the form of files. At this time, we can use localStorage in Javascript to access data. In this post you will learn: ① How to use localStorage?  ② How to save and read strings via localStorage? ③ How to store and read Json objects through localStorage?

Keywords: Javascript , cookie data , localStorage , setItem , getItem.

Basic use of localStorage

Data in javascript can be easily accessed using the localStorage.setItem() and localStorage.getItem() functions. It should be noted that when using localStorage.getItem(), it is necessary to determine whether the data of the given name exists.

Json objects

When using localStorage to save a Json object, you need to format the Json object as a string with JSON.stringify() before storing, and after reading the Json object cache, you need to reformat it with JSON.parse().

Accessing data in the website can be achieved by using setItem(), getItem(), clear(), removeItem() of localStorage. It should be noticed that when processing Json objects, you need to combine JSON.stringify() and JSON.parse () to format the data.

Edit Template

Leave a Reply

Your email address will not be published. Required fields are marked *

Chaoxu Wei

Master student at Tongji University (Writer & Blogger)

Job hunting, both part-time and full-time jobs are accepted. Job recommendation please email me weichaoxu1998@gmail.com, thank you very much!

0
0
Edit Template

“There are many people in the world who want to work hard but can’t, and people who work too hard and are exhausted. Please don’t use your efforts only to chase your own victory, please use them to help others.”

Follow

Contact

libertynlp@163.com

+86-18385537403

Yangpu District, Shanghai