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.