Example Analysis of localStorage Object Storage Mode in JavaScript

  • 2021-07-10 18:39:49
  • OfStack

This paper describes the storage mode of localStorage objects in JavaScript. Share it for your reference, as follows:

[Local storage limitations] The article mentioned the limitation of local storge in JavaScript. In the example, one bool data was stored in localStorage, but it was not stored as we expected.

When we store Boolean, numeric, and string types, the localStorage object defaults our stored data to string literals.


localStorage[0] = false;// "false"
localStorage[1] = 1200;// "1200"
localStorage[2] = "wtf";// "wtf"

There seems to be nothing above, just Boolean data failure. What if we change the stored data to other types? Such as arrays, literal objects, Object and so on.


var obj=new Object();
obj.name="obj";
obj.type="obj";
localStorage[3] = ["160","170","180"];// "160,170,180"
localStorage[4] = {"id":"0001","name":"lee"};// "[object Object]"
localStorage[5] = obj;// "[object Object]"

Here, the Object object is dumped as a type string. So when storing data such as objects, you need to use JSON. stringify, JSON. parse to turn it into a string before trying to restore the data.

More readers interested in JavaScript can check the topics of this site: "javascript Object-Oriented Introduction Tutorial", "JavaScript Search Algorithm Skills Summary", "JavaScript Data Structure and Algorithm Skills Summary", "json Operation Skills Summary in JavaScript", "JavaScript Error and Debugging Skills Summary" and "JavaScript Mathematical Operation Usage Summary"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: