Localstorage.setitem (att) automatically stores att as a string, such as:
The code is as follows |
Copy Code |
var arr=[1,2,3]; Localstorage.setitem ("temp", arr); typeof Localstorage.getitem ("temp"); Returns a string Localstorage.getitem ("temp"); returns 1,2,3 |
It is worth noting, however, that Localstorage.setitem () does not automatically turn the JSON object into a string, such as:
The code is as follows |
Copy Code |
var obj={"A": 1, "B": 2]; Localstorage.setitem ("Temp2", obj); typeof Localstorage.getitem ("Temp2"), also returns a string Localstorage.getitem ("temp"), but returns [Object Object] |
The correct way to store the JSON object using Localstorage.setitem () is to convert the JSON object to a string using the Json.stringify () method before storage, such as:
The code is as follows |
Copy Code |
var obj={"A": 1, "B": 2}; Obj=json.stringify (obj); Localstorage.setitem ("Temp2", obj); typeof Localstorage.getitem ("Temp2"); return string Localstorage.getitem ("Temp2"); return string format: {"A": 1, "B": 2} |
To manipulate the JSON object later, it is natural to convert the previously stored JSON string into a JSON object and then manipulate it, such as:
The code is as follows |
Copy Code |
Obj=json.parse (Localstorage.getitem ("Temp2")); |
After the operation, storage information, remember to convert the format: obj=json.stringify (obj);
In addition: Localstorage.getitem (ATT), if ATT is not defined, returns a null value instead of the undefined