How can I store and retrieve many javascript primi

2019-09-02 18:03发布

问题:

My application has the following Javascript primatives:

var bearerToken = "a";
var expirationDate = "b";
var firstName = "c";
var authenticated = true;
var lastName = "d";
var loginMessage = "e";
var name = "f";
var registrationMessage = "g";
var roleId = 1;
var subjectId = 2;
var userName = "h"

I would like to hold a copy of these in local storage. I know how to do it for one at a time but is there a way I could do it for all of them at the same time?

回答1:

The easiest way would be to use JSON.stringify and store the object as a string. Use JSON.parse to retrieve it:

var o = {
    bearerToken: 'Foo',
    authenticate: true,
    subjectId: 3
}
localStorage.setItem('myData', JSON.stringify(o));
console.log(JSON.parse(localStorage.getItem('myData')));


回答2:

Make an object and store them on the same object

var someObj = {lastName:'test',firstname:'joe'};

Just add all the properties to the object like above.

You can store it as a json string

localStorage.setItem('someName', JSON.stringify(someObj));


回答3:

localStorage.setItem("bearerToken","") will help you to save an item in the local storage. localStorage.getItem("bearerToken") will retrieve that value localStorage.removeItem("bearerToken") will remove that item.