gpt4 book ai didi

javascript - 在 localStorage 中存储和检索

转载 作者:行者123 更新时间:2023-11-28 07:26:39 25 4
gpt4 key购买 nike

我想将数据存储在localStorage中。我想让它像一个数据库。

这是一个示例。用户将创建一个电子测试;它将有标题和描述。不止一个问题,每个问题都有多个选择。

其他用户可以创建另一个电子测试。我如何将其存储在 localStorage 中?

目前我正在这样做:

KEY                | VALUES
----------------------------------------------------------
Tests | ["Sample","Sample2","Sample3"]
----------------------------------------------------------
Description | ["Sample","Sample2","Sample3"]
----------------------------------------------------------
Sample2 | ["question1","question2","question3"]
----------------------------------------------------------
question3 | ["Question","choice1","choice2","choice3"]
----------------------------------------------------------
question3_ifAnswer | ["","","yes","yes"]
----------------------------------------------------------

我认为有更好的方法来存储它。顺便说一句,问题是动态添加的,以及每个问题中的选择。

如何以更好的方式存储和检索它?

最佳答案

作为一组数组,这看起来确实很难管理。

我可能会将其存储为这样的 JavaScript 对象,然后将其转换为 json 并将生成的 json 强存储在 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);

显然我只能猜测你的意图,因此你需要调整它以满足你的需求

当您从 localStorage 中将其作为 JSON 字符串检索时,使用

将其转换回对象/数组
tests = JSON.parse(jsonstr);

关于javascript - 在 localStorage 中存储和检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29586011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com