简体   繁体   English

离线版Webapp-存储JavaScript对象

[英]Offline webapp - Storing JavaScript objects

I'd like to make a simple web browser console program that would run COMPLETELY OFFLINE. 我想制作一个简单的Web浏览器控制台程序,该程序可以完全离线运行。

In that program, I'd like to store some data in the form of an array of objects so that I could easily pick a random object. 在该程序中,我想以对象数组的形式存储一些数据,以便可以轻松选择随机对象。

My problem is that even though I looked up the internet, including this question Storing Objects in HTML5 localStorage and this question Offline webapp. 我的问题是,即使我查找了Internet,也包括了在HTML5 localStorage中存储对象离线Webapp这个问题 How to store data? 如何存储数据? , I still don't have any clue of what to do. ,我仍然不知道该怎么办。

I'd like to find a way to easily add objects to my array and save those changes so that when I open the browser again, the data set would be intact. 我想找到一种轻松地将对象添加到数组中并保存这些更改的方法,以便当我再次打开浏览器时,数据集将保持完整。

I understand that HTML5's local storage only stores data in the form of strings, so what should I do ? 我了解HTML5的本地存储仅以字符串形式存储数据,那该怎么办?

Should I use Node.js ? 我应该使用Node.js吗? If so, how can I send back the data to my web browser Javascript file so that I can display things in the browser ? 如果是这样,如何将数据发送回Web浏览器Javascript文件,以便可以在浏览器中显示内容?

You can serialize your array of objects using JSON.stringify so that it is stored as a string in Web Storage and deserialize it upon retrieval using JSON.parse : 您可以使用JSON.stringify序列化对象数组,以便将其作为字符串存储在Web Storage中,并在使用JSON.parse检索时反序列化:

var arrayOfObjects = [
    { foo: 'hello' },
    { bar: 'world' },
    { baz: 'dinosaurs' }
];

function storeInWebStorage(key, arr) {
    localStorage.setItem(key, JSON.stringify(arr));
}

function retrieveFromWebStorage(key) {
    return JSON.parse(localStorage.getItem(key));
}

storeInWebStorage(arrayOfObjects);

Keep in mind though that there's a limit on the amount of data you can store in Web Storage , and this limit differs between browsers. 请记住,尽管您可以在Web Storage中存储的数据量有限制 ,并且此限制在不同的浏览器中有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM