How can I store and retrieve many javascript primitives in and from local storage

有些话、适合烂在心里 提交于 2019-12-25 06:48:05

问题


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.



来源:https://stackoverflow.com/questions/27119400/how-can-i-store-and-retrieve-many-javascript-primitives-in-and-from-local-storag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!