If you try to store object with Localstorage, you accidentally find out that it's not what you want, such as:
Stores an object and assigns the value of the Name property of the object to the P label.
Html:
< P > </ P >
Js:
var fruit={ name:' Apple ', color:' red ', taste:' sweet ' } localstorage.myfruit=fruit; Console.log (localstorage.myfruit); document.getElementsByTagName (' P ') [0].innerhtml=localstorage.myfruit.name;
Results:
At this point you will find that the value of name cannot be taken out. So we need to do something extra when we access the object, as follows:
Js:
var fruit={
Name: ' Apple ',
Color: ' Red ',
Taste: ' Sweet '
}
Localstorage.myfruit=json.stringify (fruit); //Convert object type to String type store
Console.log (Localstorage.myfruit);
var obj=json.parse (localstorage.myfruit); //re-parses the string into a JSON object
document.getElementsByTagName (' P ') [0].innerhtml=obj.name;
Results:
Conclusion:
When you use Localstorage for storage, you need to use the Json.stringify () method to convert an object to string and then store it.
You need to use the Json.parse () method to return a string to object when the value is taken.
Questions about Localstorage storing JSON objects