如何在本地存储中以及从本地存储中存储和检索许多JavaScript原语 [英] How can I store and retrieve many javascript primitives in and from local storage

查看:133
本文介绍了如何在本地存储中以及从本地存储中存储和检索许多JavaScript原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序具有以下Javascript基元:

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?

推荐答案

最简单的方法是使用JSON.stringify并将对象存储为字符串.使用JSON.parse进行检索:

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')));

这篇关于如何在本地存储中以及从本地存储中存储和检索许多JavaScript原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆