[英]Storing and retrieving in localStorage
I want to store data in localStorage. 我想将数据存储在localStorage中。 I want to make it like a database.
我想使其像数据库一样。
Here is a sample. 这是一个样本。 A user will create an electronic test;
用户将创建一个电子测试; it will have a Title and Description.
它将具有标题和描述。 More than one question, each with more than one choice.
一个以上的问题,每个问题都有多个选择。
Another user can create another electronic test. 另一个用户可以创建另一个电子测试。 How am I going to store it in localStorage?
如何将其存储在localStorage中?
Currently I am doing it like this: 目前,我正在这样做:
KEY | VALUES
----------------------------------------------------------
Tests | ["Sample","Sample2","Sample3"]
----------------------------------------------------------
Description | ["Sample","Sample2","Sample3"]
----------------------------------------------------------
Sample2 | ["question1","question2","question3"]
----------------------------------------------------------
question3 | ["Question","choice1","choice2","choice3"]
----------------------------------------------------------
question3_ifAnswer | ["","","yes","yes"]
----------------------------------------------------------
I think there is a better way to store it. 我认为有更好的存储方式。 By the way, the question is dynamically added, as well as the choices in each questions.
顺便说一句,该问题以及每个问题中的选择都是动态添加的。
How do I store and retrieve it in a better way? 如何更好地存储和检索它?
That does look difficult to manage as a bunch of arrays. 作为一堆数组,这确实很难管理。
I would probably store it as a javascript object like this, then convert it to json and store the resulting json strong in localStorage. 我可能会将其存储为这样的javascript对象,然后将其转换为json并将结果json存储在localStorage中。
I assume you understand the limitations of localStorage 我假设您了解localStorage的局限性
var tests = [
{
title: "title 1",
description: "Desc 1",
questions: [
{
name: "question 1",
type: "text"
},
{
name: "question 2",
type: "multiple choice",
options: [
{
code: "A",
description: 'Choice A'
},
{
code: "B",
description: 'Choice B'
},
{
code: "C",
description: 'Choice C'
}
],
answer: ""
}
]
},
{
title: "test 2",
description: "Desc for test 2",
questions: [], //etc
answer: ""
}
];
var jsonstr = JSON.stringify(tests);
Obviously I can only guess at you intentions so you would need to adjust this to suit your needs 显然,我只能猜测您的意图,因此您需要进行调整以适合您的需求
And when you retrieve it as a JSON string from localStorage, convert it back to an object/ array with 当您从localStorage中将其作为JSON字符串检索时,请使用以下命令将其转换回对象/数组
tests = JSON.parse(jsonstr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.